javascript - 正则表达式:在引号内为每个单词添加前缀

标签 javascript regex

使用 javascript 和正则表达式,我想在引号内的每个单词前加上一个加号。

给定以下字符串:

"this is in quotes" not in quote "more quotes"

我想返回:

"+this +is +in +quotes" not in quote "+more +quotes"

之后,我想删除所有引号,这使用简单的替换不是问题,但如果这一切都可以在一个正则表达式中完成,那就太酷了。

我知道我可以使用 \"(.*?)\"选择引号中的所有内容,然后 (?<![^ ])(?=[^ ])选择每个单词的开头,但我不知道如何将它们放在一起。

最佳答案

您可以使用一个正则表达式来做到这一点!

这个想法是向前看,只匹配后面跟着“...chars quote valid-string”的单词,其中“valid-string”不包含引号或平衡的引号对。

quotes_re = `
    \\w+          # a word

    (?=           # followed by ..

        [^"]*     # plain text (possibly empty), and then...
        "         # a quote, and then...
        (
            [^"]+      # some plain text
            |          # or
            " [^"]* "  # a quoted string
        )*             # 0 or more times
        
        $         # end of string    
    )
`;

let regex = (src, flags) => 
     new RegExp(src.replace(/#.*|\s+/g, ''), flags);

s = '"this is in quotes" not in quote "more quotes" end end'

console.log('regex', regex(quotes_re, 'g').source)
console.log('result', s.replace(regex(quotes_re, 'g'), '+$&'))

regex 实用程序为 JS 提供详细的正则表达式支持,您可以通过登录 regex(quotes_re, 'g').source 获取原始源代码

关于javascript - 正则表达式:在引号内为每个单词添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377791/

相关文章:

c# - 使用正则表达式删除 css 注释

Python - 使用 RegEx 操作字符串

python - 在Python中使用正则表达式来匹配单词

javascript - 显示/隐藏下拉选项取决于另一个下拉选项

javascript -//用来代替http ://on src ="" attribute

javascript - 使用 JS 删除表上的范围

jQuery:replace() 类名/正则表达式

javascript - 计算 Javascript 中正则表达式的匹配次数

javascript - React 从另一个文件夹导入组件问题

javascript - 使用 jQuery 在 span 中添加一个 ✔ 刻度线