2011-02-07 72 views
2

我有一個正則表達式,它是[\\.|\\;|\\?|\\!][\\s]
這是用來分割一個字符串。但是如果它在引號中,我不希望它分裂. ; ? !RegEx忽略引號之間的文本

+2

我想你需要開始思考*解析*,不是正則表達式分裂。儘管如此,這將更容易回答一些示例輸入。 – deceze 2011-02-07 03:56:10

回答

6

我不想使用拆分,而是使用模式&匹配器。

一個演示:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Main { 

    public static void main(String[] args) { 

     String text = "start. \"in quotes!\"; foo? \"more \\\" words\"; bar"; 

     String simpleToken = "[^.;?!\\s\"]+"; 

     String quotedToken = 
       "(?x)    # enable inline comments and ignore white spaces in the regex   \n" + 
       "\"    # match a double quote            \n" + 
       "(    # open group 1              \n" + 
       " \\\\.   # match a backslash followed by any char (other than line breaks) \n" + 
       " |    # OR                \n" + 
       " [^\\\\\r\n\"] # any character other than a backslash, line breaks or double quote \n" + 
       ")    # close group 1              \n" + 
       "*    # repeat group 1 zero or more times         \n" + 
       "\"    # match a double quote            \n"; 

     String regex = quotedToken + "|" + simpleToken; 

     Matcher m = Pattern.compile(regex).matcher(text); 

     while(m.find()) { 
      System.out.println("> " + m.group()); 
     } 
    } 
} 

主要生產:

> start 
> "in quotes!" 
> foo 
> "more \" words" 
> bar 

正如你所看到的,它也可以處理引用令牌裏面轉義引號。

0

這是我爲了忽略匹配中的引號而做的。

(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*? # <-- append the query you wanted to search for - don't use something greedy like .* in the rest of your regex. 

要爲您的正則表達式適應這一點,你可以做

(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*?[.;?!]\s*