2012-01-06 36 views
5

我想使用正則表達式來處理Java中的字符串。目標是找到所有$標誌的前面有偶數\(或沒有),然後再添加\正則表達式(Java)查找其他字符前偶數的所有字符

例子:

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

應導致:

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

理由這裏是:一些$已經逃脫了\和一些逃生\可能是字符串,以及形式\ \。我需要逃避剩餘的$。

回答

8

這應該做的工作:更換。

插圖在Perl:

$ 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 

使用Java,整個文本匹配$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

我覺得這樣的事情可能工作:與匹配(除先行)的全部文本,然後\\

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

\$(\\\\)*\\ 
相關問題