2016-01-22 97 views
0

我有一個字符串,讓說: "The student John with the number 1 is smart."用java模式從字符串中提取一個可變的字符串,數字和匹配器

我想提取該字符串變量部分:學生的姓名和他數。

  • "The student John with the number 1 is smart."
  • "The student Alan with the number 2 is smart."

我應該如何創建正則表達式?我知道\\d提取數字,但我如何提取字符串?

  • but for the "**H2k Gaming** (1st to **5** Kills)"

    其中變量字符串是 「H2K遊戲」 和可變數量是5

    String sentence = "H2k Gaming (1st to 5 Kills)"; 
    String pattern = "[\\w ]+ \\(1st to (\\d+) Kills\\)"; 
    

它打印:

Name: Gaming 
Number: 5 

回答

2
String sentence = "The student John with the number 1 is smart."; 
String pattern = "The student (\\w+) with the number (\\d+) is smart."; 

Pattern r = Pattern.compile(pattern); 
Matcher m = r.matcher(sentence); 

if(m.find()) { 
    System.out.println("Name: " + m.group(1)); 
    System.out.println("Number: " + m.group(2)); 
} 

See it in action

+1

@NellyJunior,在這種情況下它不會工作,因爲'H2K Gaming'中有空間。 '\ w'匹配一個字母,數字或短劃線。要添加空間,您可以用'[\\ w] +'替換'\\ w +'。這將創建一個字符集,它接受'\\ w'和空格。 – ndn

+0

我編輯了這個問題。其餘部分不起作用。你能告訴我爲什麼嗎?謝謝! –

+0

@NellyJunior,你仍然需要在字符集周圍加上'()'。 [查看更新後的版本](https://repl.it/BgDe/1) – ndn

1

如果字符串始終具有相同的格式,你可以簡單地通過" "分裂和訪問權指標:

String[] tokens = text.split(" "); 
String name = tokens[2]; 
int number = Integer.parseInt(tokens[6]); 
0

只要形式是不變的,只是拿到空白。

^The student (.*) with the number (.*) is smart\.$