2017-03-06 2 views
-1

J'ai une phrase comme ceci:Java: Couper un numéro après un mot spécifique dans une phrase

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; 

Comment puis-je couper seulement nombre123 après le mot sample?

+2

vous pouvez utiliser une expression régulière ' "échantillon. * (\\ d +)"' un matcher. –

+0

Passez par regex..https. //docs.oracle.com/javase/tutorial/essential/regex/ – Akshay

+0

@PeterLawrey votre solution sera de retour '3' à la place, vous devriez d'enlever le' '' "échantillon (\\ d +) "' –

Répondre

0

simple exemple regexp. (Dans le monde réel traiterait différemment avec des freins et contrepoids.)

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

il va en fait courir une fois et retourner la première occurrence de 123 – 7663233

0

Vous pouvez utiliser regex, donc si votre regard votre numéro existant entre sample et space de sorte que vous pouvez utiliser ceci:

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

vous pouvez également utiliser la solution de @Peter Lawrey supprimer juste le *

Pattern PATTERN = Pattern.compile("sample.(\\d+)"); 
Matcher matcher = PATTERN.matcher(input); 

// Check for matches 
while (matcher.find()) { 
    keywords.add(matcher.group(1)); 
}