2011-02-07 9 views
2

私はRegexを持っています[\\.|\\;|\\?|\\!][\\s]
これは文字列を分割するために使用されます。しかし、それが引用符で囲まれている場合、それを分割することは望ましくありません。. ; ? !RegEx引用符間のテキストを無視する

+2

を行うことができ、私はあなたが*解析*、ではない正規表現の分割について考え始める必要があると思います。これは、たとえいくつかの入力例で答える方が簡単です。 – deceze

+0

解析はオプションですが、私はRegExでそれを行う方法を知りたいと思います。彼らはこれを行う方法ですか? –

+0

RegExはこれを使用するツールではありません。使用するツールの種類にかかわらず、構文解析の代替手段ではありません。私はあなたがこのクエストをあきらめ、上記のように解析する必要があると思います。 –

答えて

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* 
関連する問題