Javascript:仅替换某些短语中的字母

标签 javascript regex

结束here我被要求用我的评论之一形成一个新问题,所以我来了。我想知道是否可以只替换某些单词中的短语。例如:替换 CBABAC 中的 BAB 但不替换 DABABCC 中的 BAB 谢谢!

最佳答案

使用 lookahead :

BAB(?=AC)

解释

"BAB" +      // Match the characters “BAB” literally
"(?=" +      // Assert that the regex below can be matched, starting at this position (positive lookahead)
   "AC" +       // Match the characters “AC” literally
")"  

BAB(?!CC)

解释

"BAB" +      // Match the characters “BAB” literally
"(?!" +      // Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   "CC" +       // Match the characters “CC” literally
")"  

关于Javascript:仅替换某些短语中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692800/

相关文章:

javascript - 理解 require.js 来实现backbone.js

c# - 减少 regex/linq 的 2 GB 内存占用或解决获取不同组值的问题

python - 在 Pandas 中使用逗号将整列整数转换为千位分隔的字符串

javascript - 创建一个正则表达式来查找逗号分隔的字符串而不重复中心部分

javascript - RegEx ip/mask(例如:192.168.1.1/24)

javascript - 在表单提交jquery之前删除空值

javascript - setState 在单独文件中的非 React 组件中

javascript - PeerConnection 创建不完整的报价

javascript - 当我不想让一个函数再次运行时,如何停止它? (jquery)

php - 正则表达式 - 量词的目标无效