替换除撇号之间的所有下划线(Java,String)

时间:2013-09-29 19:44:01

标签: java regex

我需要替换字符串中的所有下划线,除了那些落在两个撇号范围内的下划线。例如:

"first_name" => "first name"
"code_numbers = '123_456'" => "code numbers = '123_456'"

我目前正在使用.replaceAll(“_”,“”)丢弃所有下划线,因为它们并不是非常常见,但我现在想要触及所有基础以防万一。

2 个答案:

答案 0 :(得分:4)

这应该有用(这个正则表达式替换所有_后跟偶数个单引号)。当然,这需要你的报价平衡:

String str = "\"code_numbers = '123_456'\"";

str = str.replaceAll("(?x) " + 
               "_          " +   // Replace _
               "(?=        " +   // Followed by
               "  (?:      " +   // Start a non-capture group
               "    [^']*  " +   // 0 or more non-single quote characters
               "    '      " +   // 1 single quote
               "    [^']*  " +   // 0 or more non-single quote characters
               "    '      " +   // 1 single quote
               "  )*       " +   // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
               "  [^']*    " +   // Finally 0 or more non-single quotes
               "  $        " +   // Till the end  (This is necessary, else every _ will satisfy the condition)
               ")          " ,   // End look-ahead
                       "");      // Replace with ""

答案 1 :(得分:1)

恢复这个问题,因为它有一个简单的正则表达式解决方案,没有提到。 (在为regex bounty quest进行一些研究时找到了您的问题。)

'[^']*'|(_)

交替的左侧与完成'single quoted strings'匹配。我们将忽略这些匹配。右侧匹配并捕获第1组的下划线,我们知道它们是正确的下划线,因为它们与左侧的表达式不匹配。

以下是工作代码(请参阅online demo):

import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;

class Program {
public static void main (String[] args) throws java.lang.Exception  {

String subject = "code_numbers = '123_456'";
Pattern regex = Pattern.compile("'[^']*'|(_)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
    if(m.group(1) != null) m.appendReplacement(b, " ");
    else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);
} // end main
} // end Program

参考

  1. How to match pattern except in situations s1, s2, s3
  2. How to match a pattern unless...
相关问题