Java:在一个句子中的特定单词之后剪切一个数字

时间:2017-03-06 09:28:06

标签: java numbers substring word sentence

我有这样一句话:

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

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式,因此,如果您在samplespace之间查看您的号码,那么您可以使用此功能:

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));
}