我有这样一句话:
String str = "This is a sample 123 string 456. And continue 123...";
// OR
String str = "This is another sample 123 and other words. And 123";
// I want => int result = 123;
如何在字 123
之后仅剪切数字 sample
?
答案 0 :(得分:0)
您可以使用正则表达式,因此,如果您在sample
和space
之间查看您的号码,那么您可以使用此功能:
public static final String REGEX_START = Pattern.quote("sample ");
public static final String REGEX_END = Pattern.quote(" ");
public static final Pattern PATTERN = Pattern.compile(REGEX_START + "(.*?)" + REGEX_END);
public static void main(String[] args) {
String input = "This is a sample 123 string 456. And continue 123...";
List<String> keywords = new ArrayList<>();
Matcher matcher = PATTERN.matcher(input);
// Check for matches
while (matcher.find()) {
keywords.add(matcher.group(1));
}
keywords.forEach(System.out::println);
}
或者您可以使用@Peter Lawrey的解决方案删除*
Pattern PATTERN = Pattern.compile("sample.(\\d+)");
Matcher matcher = PATTERN.matcher(input);
// Check for matches
while (matcher.find()) {
keywords.add(matcher.group(1));
}