REGEX 异常替换
REGEX Replacing with exception
我的第一个问题是我的克星正则表达式。
我需要一个正则表达式来用文本中的 ","
替换每个 ,
,而不替换现有的 ,"
.
看起来像这样:
之前:
abcd,efgh,ijkl,"","",mnop
之后:
abcd","efgh","ijkl","","","mnop
希望你能帮帮我。
粗略地说,我认为您在寻找类似的东西:
(?:(?<!"),"|(?<=")",(?!")|(?<!"),(?!"))
注意: 正如@WiktorStribiżew 在评论中提到的那样,您可以摆脱外部非捕获组:(?<!"),"|(?<=")",(?!")|(?<!"),(?!")
在线查看Demo
使用正则表达式解决问题很好but now you have two problems。
一个不涉及使用正则表达式的简单解决方案是进行三个简单的字符串替换:首先将 ,
替换为 ","
然后将 ",""
替换为 ","
最后 "","
和 ","
.
让我们看看为什么会这样:
| after 1st | after 2nd | after 3rd
original | replacement | replacement | replacement
----------+-------------+-------------+-------------
a,b | a","b | a","b | a","b
m",n | m"","n | m"","n | m","n
x,"y | x",""y | x","y | x","y
查看实际效果:
const input = 'abcd,efgh,ijkl,"","",mnop';
const output = input.replace(/,/g, '","').replace(/",""/g, '","').replace(/"","/g, '","');
console.log(output);
N.B。上面的代码片段使用正则表达式,因为这是 JavaScript 实现“全部替换”功能的方式。当 String.replace()
的第一个参数是一个字符串时,它只替换它的第一次出现。
我还可以使用 String.replaceAll()
instead (it works with strings) but it is not widely supported by browsers。
我的第一个问题是我的克星正则表达式。
我需要一个正则表达式来用文本中的 ","
替换每个 ,
,而不替换现有的 ,"
.
看起来像这样:
之前:
abcd,efgh,ijkl,"","",mnop
之后:
abcd","efgh","ijkl","","","mnop
希望你能帮帮我。
粗略地说,我认为您在寻找类似的东西:
(?:(?<!"),"|(?<=")",(?!")|(?<!"),(?!"))
注意: 正如@WiktorStribiżew 在评论中提到的那样,您可以摆脱外部非捕获组:(?<!"),"|(?<=")",(?!")|(?<!"),(?!")
在线查看Demo
使用正则表达式解决问题很好but now you have two problems。
一个不涉及使用正则表达式的简单解决方案是进行三个简单的字符串替换:首先将 ,
替换为 ","
然后将 ",""
替换为 ","
最后 "","
和 ","
.
让我们看看为什么会这样:
| after 1st | after 2nd | after 3rd
original | replacement | replacement | replacement
----------+-------------+-------------+-------------
a,b | a","b | a","b | a","b
m",n | m"","n | m"","n | m","n
x,"y | x",""y | x","y | x","y
查看实际效果:
const input = 'abcd,efgh,ijkl,"","",mnop';
const output = input.replace(/,/g, '","').replace(/",""/g, '","').replace(/"","/g, '","');
console.log(output);
N.B。上面的代码片段使用正则表达式,因为这是 JavaScript 实现“全部替换”功能的方式。当 String.replace()
的第一个参数是一个字符串时,它只替换它的第一次出现。
我还可以使用 String.replaceAll()
instead (it works with strings) but it is not widely supported by browsers。