我需要替换字符串中的所有下划线,除了那些落在两个撇号范围内的下划线。例如:替换除撇号之外的所有下划线(Java,字符串)
"first_name" => "first name"
"code_numbers = '123_456'" => "code numbers = '123_456'"
我目前只是扔掉使用.replaceAll(“_”,““)的所有下划线,因为它们不是非常普遍的,但我想现在去触摸所有基地,以防万一。
我需要替换字符串中的所有下划线,除了那些落在两个撇号范围内的下划线。例如:替换除撇号之外的所有下划线(Java,字符串)
"first_name" => "first name"
"code_numbers = '123_456'" => "code numbers = '123_456'"
我目前只是扔掉使用.replaceAll(“_”,““)的所有下划线,因为它们不是非常普遍的,但我想现在去触摸所有基地,以防万一。
复活这个问题,因为它已经陷入未提及的简单的regex解决方案。 (发现你的问题而做一些研究的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
参考
这应该工作(这个正则表达式替换所有的_,后面跟着偶数个单引号)。当然,这需要你的报价要进行平衡:
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 ""
你与说明用什么编辑器? –
@MaximShoustin。没有。用手写。 –
@MaximShoustin。它在开头是'(?x)'修饰符,它允许你用空格编写正则表达式。 –