4

入力文字列があります

これまたは「それまたは」または「これまたはそれ」

に翻訳する必要があります

|| これ || || 「それか」|| "これかそれか"

そのため、文字列内で文字列 ( または ) の出現を探し、それを別の文字列 ( || ) に置き換えようとします。次のコードを試しました

Pattern.compile("( or )(?:('.*?'|\".*?\"|\\S+)\\1.)*?").matcher("this or \"that or\" or 'this or that'").replaceAll(" || ")

出力は

|| これ || || 「それか」|| 'これ || それ'

問題は、一重引用符内の文字列も置き換えられたことです。コードに関しては、スタイルは単なる例です。パターンをコンパイルして、これが機能するようになったら再利用します。

4

1 に答える 1

10

Try this regex: -

"or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"

It matches or which is followed by any characters followed by a certain number of pairs of " or ', followed by a any characters till the end.

String str = "this or \"that or\" or 'this or that'";
str = str.replaceAll("or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)", "||");        
System.out.println(str);

Output : -

this || "that or" || 'this or that'

The above regex will also replace or, if you have a mismatch of " and '.

For e.g: -

"this or \"that or\" or \"this or that'"

It will replace or for the above strings also. If you want it not to replace in the above case, you can change the regex to: -

str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");
于 2012-12-06T08:56:56.880 に答える