2012-01-06 5 views
5

Regexを使用してJavaのStringを操作したいと思います。目標は、\の偶数がある(またはまったくない)すべての$記号を見つけてから、もう一度\を追加することです。Regex(Java)は、先行するすべての文字を他の文字の偶数で検索します。

例:

"$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" 

が生じるはずである:ここ

"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" 

理論的根拠は次のとおりです。すでに\といくつかのエスケープ\でエスケープされているいくつかの$の形式で、同様の文字列であるかもしれません\\。私は残りの$をエスケープする必要があります。

答えて

8

:置き換える:

(^|[^\\])(\\{2})*(?=\$) 

\\続く(先読みを除く)マッチしたテキスト全体、と。 Perlで

イラスト:Javaを使用し

$ perl -pe 's,(^|[^\\])(\\{2})*(?=\$),$&\\,g' 
"$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" # in... 
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" # out 
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" # in... 
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" # out 

、全体のテキストマッチが$0です。サンプルコード:

// package declaration skipped 
import java.util.regex.Pattern; 

public final class TestMatch 
{ 
    private static final Pattern p 
     = Pattern.compile("(^|[^\\\\])(\\\\{2})*(?=\\$)"); 

    public static void main(final String... args) 
    { 
     String input = "\"$ Find the $ to \\$ escape \\\\$ or not \\\\\\$ " 
      + "escape \\\\\\\\$ like here $\""; 

     System.out.println(input); 

     // Apply a first time 
     input = p.matcher(input).replaceAll("$0\\\\"); 
     System.out.println(input); 

     // Apply a second time: the input should not be altered 
     input = p.matcher(input).replaceAll("$0\\\\"); 
     System.out.println(input); 
     System.exit(0); 
    } 
} 

出力:

"$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" 
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" 
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$" 

使用正規表現について少し説明が順序である:

   # begin regex: 
(    # start group 
    ^   # find the beginning of input, 
    |   # or 
    [^\\]  # one character which is not the backslash 
)    # end group 
       # followed by 
(    # start group 
    \\{2}  # exactly two backslashes 
)    # end group 
*    # zero or more times 
       # and at that position, 
(?=    # begin lookahead 
    \$   # find a $ 
)    # end lookahead 
       # end regex 

ここでは、実際に完全にするために正規表現での位置でありますエンジンは一致するテキスト(<>で表されます)とカーソル位置(|によって象徴されます):

# Before first run: 
|"$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" 
# First match 
"<>|$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" 
# Second match 
"$ Find the <>|$ to \$ escape \\$ or not \\\$ escape \\\\$ like here $" 
# Third match 
"$ Find the $ to \$ escape <\\>|$ or not \\\$ escape \\\\$ like here $" 
# Fourth match 
"$ Find the $ to \$ escape \\$ or not \\\$ escape <\\\\>|$ like here $" 
# From now on, there is no match 
0

は、私はこのような何かがうまくいくかもしれないと思う:これは、作業を行う必要があります

\$(\\\\)*\\ 
関連する問題