1

私のファイルには次のような行が含まれています

"This is a string." = "This is a string's content."
" Another \" example \"" = " New example."
"My string
can have several lines." = "My string can have several lines."

部分文字列を抽出する必要があります:

This is a string.
This is a string's content.
 Another \" example \"
 New example.
My string
can have several lines.
My string can have several lines.

これが私のコードです:

String regex = "\".*?\"\\s*?=\\s*?\".*?\"";
Pattern pattern = Pattern.compile(regex,Pattern.DOTALL);
Matcher matcher = pattern.matcher(file);

今のところ、「=」の左右の部分のペアを取得できます。しかし、サブストリングに「\」が含まれていると、正規表現が正しく機能しません。

誰かが正しい正規表現を書くのを手伝ってもらえますか?\"の代わりに\"^[\\ "]を試しましたが、うまくいきませんでした。

よろしくお願いします。

4

3 に答える 3

3
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
    "\"          # Match a quote\n" +
    "(           # Capture in group number 1:\n" +
    " (?:        # Match either...\n" +
    "  \\\\.     # an escaped character\n" +
    " |          # or\n" +
    "  [^\"\\\\] # any character except quotes or backslashes\n" +
    " )*         # Repeat as needed\n" +
    ")           # End of capturing group\n" +
    "\"          # Match a quote", 
    Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group(1));
} 
于 2012-09-12T09:44:54.203 に答える
0

私はこれをテストできない場所にいることを残念に思いますが、

\".*?(?:[^\\]\")\\s*=\\s*\".*?(?:[^\\]\")

仕事?

をに置き換えた \" ので (?:[^\\]\") 、前の文字が\もう一致しない場合は一致しません。

于 2012-09-12T09:39:20.427 に答える
-1
/"([^"\\]*(?:\\.[^"\\]*)*)"/

ソースこの前の質問も参照してください

于 2012-09-12T09:58:26.847 に答える