2012-04-01 38 views
0

給定一個字符串:如何終止Java中的正則表達式匹配?

hello"this is a test"this is another test"etc 

我怎麼能寫"之前選擇什麼,然後開始移動到下一個比賽一個正則表達式?所以在最後,我得到下面的比賽:

hello 
this is a test 
this is another test 
etc 

回答

2

你可能會喜歡[^"]+

重複一次或多次來尋找的東西,這不是一個"

例如任何字符:

String s = "hello\"this is a test\"this is another test\"etc"; 
Matcher matcher = Pattern.compile("[^\"]+").matcher(s); 
while (matcher.find()) { 
    System.out.println(s.substring(matcher.start(),matcher.end())); 
} 

會產生:

hello 
this is a test 
this is another test 
etc 
+0

您不需要轉義引號字符。 – Francisc 2012-04-01 10:32:50

+0

@Francisc:我將它轉義爲java,而不是正則表達式 - 否則它不會將它視爲字符串的結尾,並且會出現語法錯誤? – amit 2012-04-01 10:33:58

+0

我不使用Java,但它可能取決於引用上下文,在任何情況下,RegExp中都不需要引號。 – Francisc 2012-04-01 10:35:19

3

使用字符串方法 「分裂」 與「作爲分隔符

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String

編輯:

String s = "hello\"this is a test\"this is another test\"etc"; 
String matches[] = s.split("\""); 
for (String str : matches) System.out.println(str); 

hello 
this is a test 
this is another test 
etc 
+1

這不是一個匹配他想要的正則表達式,這是一個變通辦法 – amit 2012-04-01 10:34:30

+0

...實現相同(見編輯) – moodywoody 2012-04-01 10:57:06

+0

正確的,我從來沒有聲稱它是錯的 - 但它是一個解決方法,這不是OP要求的。請注意,如果OP實際上並不是真正在尋找'String's,而是爲了某些元數據,那麼創建許多'String'對象['split()'的作用]可能是不夠的。 – amit 2012-04-01 11:15:57