javascript 前后没有字符的正则表达式字符串

javascript regex string with no characters before or after

我想将 "me" 转换为 "you",而不触及其中包含 "me" 的单词,即
"awesome melon me" -> "awesome melon you"

到目前为止,我得到了负面的前瞻模式:

str.replace(/me(?![a-zA-Z])/g, 'you')

所以我得到

"awesome melon me" -> "awesoyou melon you"

已尝试 some answers,找不到符合此要求的人,在此先感谢您的帮助

您可以使用零宽度 \b 特殊符号来确保匹配 "me" 是一个完整的单词:

"awesome melon me".replace(/\bme\b/g, "you")
// returns "awesome melon you"

您可以按照其他答案中的建议使用单词边界,这也会保留 me345hello_me。如果需要更严格的匹配模式,可以捕获模式前的匹配字母,放在替换模式中。

var s = "me awesome melon me"
console.log(s.replace(/(^|[^a-zA-Z])(me)(?![a-zA-Z])/g, 'you'));

应该这样做:str.replace(\bme\b/g, 'you') - \b 寻找单词边界。