JavaScript正则表达式,用于在不包围文本时捕获单引号

javascript regex to capture single quotes when not surrounding text

本文关键字:文本 单引号 包围 正则表达式 用于 JavaScript      更新时间:2023-09-26

当双单引号不封装其他文本时,我正在尝试捕获它们。

我的目标是"你好"世界"

我已经尝试使用! 不在文本上,但这不起作用,我该如何捕获它?

var str = "hello '' ''world''"
// > hello '' ''world'' 
console.log(str.replace( /''![a-z]{1,}''/g),'');
// > hello  world
console.log(str.replace( /''/g,''));
// desired output > hello ''world''

编辑

Sorrie,我试图创建一个简单的示例并有一些适用于原始示例的答案,但我需要用 NULL 替换"而不是什么都没有,即

// desired output > hello NULL ''world''
字符

类(又名否定字符类)中的字符否定是使用^字符实现的。

因此,在您的情况下,请将!替换为 ^ .试试这个:

var str = "hello '' ''world''"
// > hello NULL ''world'' 
console.log(str.replace( /''([^a-z]{1,}'')/g,"NULL$1"));

对于更完整的示例,也许这更适合:

var str = "hello '' ''world'' ''hello'' '' world"
console.log(str.replace( /(^|[^a-z])''([^a-z]+|$)/g,"$1NULL$2"));
// > "hello NULL ''world'' ''hello'' NULL world"

你可以试试:

"hello '' ''world''".replace( /'''s*''/g,'''''');
//"hello ''world''"