2017-03-06 110 views
-1

我有这样的句子:的Java:切一个号码一个特定的单词后,在一个句子

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; 

我怎么能只砍123sample后?

+2

您可以使用正则表达式'“样本。*(\\ d +)”'有匹配器。 –

+0

浏览正则表达式.https://docs.oracle.com/javase/tutorial/essential/regex/ – Akshay

+0

@PeterLawrey您的解决方案将返回'3',而不是您应该删除'*''“样本。 d +)“' –

回答

0

简单的正则表达式示例。 (在真实的世界将与制衡不同的方式处理它。)

String regex = "(123)"; 
    String testName= "This is another sample 123 and other words. And 123"; 
    Pattern pattern = 
      Pattern.compile(regex); 
    Matcher matcher = 
      pattern.matcher(testName); 

    String res = null; 
    if (matcher.find()) { 
     res = matcher.group(1); 
    } 

    System.out.println(res); //prints 123 
+0

它实际上将运行一次并返回第一次出现123 – 7663233

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)); 
} 
相关问题