适用于 chrome 但不适用于 safari (?<![\n])[\n]{1}(?![\n])
Works with chrome but not safari (?<![\n])[\n]{1}(?![\n])
我的 Javascript 代码中有这个正则表达式 (?<![\n])[\n]{1}(?![\n])
,据我所知,Safari 不支持负向后视。
我需要做的是将所有没有被其他\n包围的\n替换成一个字符串。
有人可以帮我弄清楚如何编写正则表达式以便它可以在 Safari 中使用吗?
谢谢。
您可以捕获字符串的开头或第 1 组中的非空白字符。
然后匹配单个换行符,并断言右边不是换行符。
在替换中使用捕获组,后跟您的替换字符串 [replacement]
注意换行两边不需要方括号,可以省略{1}
(\S|^)\n(?!\n)
const regex = /(\S|^)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
const result = str.replace(regex,`[replacement]`);
console.log(result);
您的后视模式(如果支持):
const regex = /(?<!\n)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
`[replacement]`
const result = str.replace(regex,`[replacement]`);
console.log(result);
使用
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
})
JS代码:
var text = "a\nb\n\nc"
console.log(
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
}))
我的 Javascript 代码中有这个正则表达式 (?<![\n])[\n]{1}(?![\n])
,据我所知,Safari 不支持负向后视。
我需要做的是将所有没有被其他\n包围的\n替换成一个字符串。
有人可以帮我弄清楚如何编写正则表达式以便它可以在 Safari 中使用吗?
谢谢。
您可以捕获字符串的开头或第 1 组中的非空白字符。
然后匹配单个换行符,并断言右边不是换行符。
在替换中使用捕获组,后跟您的替换字符串 [replacement]
注意换行两边不需要方括号,可以省略{1}
(\S|^)\n(?!\n)
const regex = /(\S|^)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
const result = str.replace(regex,`[replacement]`);
console.log(result);
您的后视模式(如果支持):
const regex = /(?<!\n)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
`[replacement]`
const result = str.replace(regex,`[replacement]`);
console.log(result);
使用
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
})
JS代码:
var text = "a\nb\n\nc"
console.log(
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
}))