Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替换除撇号(Java,字符串)之间的下划线以外的所有下划线_Java_Regex - Fatal编程技术网

替换除撇号(Java,字符串)之间的下划线以外的所有下划线

替换除撇号(Java,字符串)之间的下划线以外的所有下划线,java,regex,Java,Regex,我需要替换字符串中的所有下划线,除了那些在两个撇号范围内的下划线。例如: "first_name" => "first name" "code_numbers = '123_456'" => "code numbers = '123_456'" 我现在只是用.replaceAll(““,”)扔掉所有下划线,因为它们不是非常常见,但我现在想用所有的基数以防万一。这应该可以用(这个正则表达式用偶数个单引号替换所有的u”)。当然,这需要您的报价保持平衡: String str = "\"

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

"first_name" => "first name"
"code_numbers = '123_456'" => "code numbers = '123_456'"
我现在只是用.replaceAll(““,”)扔掉所有下划线,因为它们不是非常常见,但我现在想用所有的基数以防万一。

这应该可以用(这个正则表达式用偶数个单引号替换所有的u”)。当然,这需要您的报价保持平衡:

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的下划线,我们知道它们是右侧的下划线,因为它们没有与左侧的表达式匹配

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

参考


  • @马克西姆舒斯汀。没有一个手写的。@maxishoustin。开头是
    (?x)
    修饰符,它允许您使用空格编写正则表达式。我知道有一个修饰符会自动给出所有这些,但不记得名称lookback会使这个10倍更容易,例如
    str=str.replaceAll((?)?
    
    '[^']*'|(_)
    
    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