2011-03-09 28 views

回答

0
Pattern pattern = Pattern.compile("_.*(\\s|\\n)"); 
Matcher matcher = pattern.matcher(_command); 

// Find all matches 
while (matcher.find()) { 
    // Get the matching string 
    String match = matcher.group(); 
}  

[A-Z]+是罰款

如果你想代碼太讓我知道

+0

'\ s'已經匹配'\ n',所以'(\ s | \ n)'是匹配'\ s'的低效方法。它仍然不會在@Peter解決方案的字符串末尾找到匹配項。 – 2011-03-10 06:46:56

-1

如果正則表達式是_.*(\s|\n)使用Java,你必須寫一樣_.*(\\s|\\n)

更新

生成的組是那些rege的部分x在括號內。所以目前只得到最後一個空格或換行符。

嘗試用這個表達式:

(_.*\\s+)

+0

不知道在java中,歡呼聲 – 2011-03-09 09:17:22

+0

'\ s'等價於'[\ t \ r \ n \ f \ v]',所以除\'s之外還匹配'\ n'或'\ r' '毫無意義。另外,OP正在嘗試在更大的字符串中查找匹配項,因此錨('^'和'$')不合適。 – 2011-03-10 06:41:30

+0

重點只是在Java中顯示反斜槓重複。最初的正則表達式來自另一個答案。不錯,它不是很精確。我會更新。 – 2011-03-10 07:07:42

1

如果您嘗試

String _command = "AFTER_2011/03/01 GREATER_2004"; 
Pattern patt = Pattern.compile("_\\S+"); 
Matcher matcher = patt.matcher(_command); 
while(matcher.find()) { 
    String name = _command.substring(matcher.start()+1, matcher.end()); 
    System.out.println(name); 
} 

它打印

2011/03/01 
2004 

編輯:由於@Alan穆爾建議你可以做到以下幾點。

String _command = "AFTER_2011/03/01 GREATER_2004"; 
Pattern patt = Pattern.compile("_(\\S+)"); 
Matcher matcher = patt.matcher(_command); 
while(matcher.find()) { 
    String name = matcher.group(1); 
    System.out.println(name); 
} 
+1

+1爲正確的正則表達式,但如果你真的需要去掉前導下劃線,爲什麼不使用'「_(\\ S +)」'並用'm.group(1)'檢索捕獲的文本? – 2011-03-10 06:30:23

+0

@Alan Moore,謝謝你的建議。我已經添加了這個作爲替代。 – 2011-03-10 09:04:46

相關問題