使用 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/