javascript - 正则表达式匹配除字符组合之外的所有内容

标签 javascript regex

我想匹配字符串中除 #*# 模式之外的所有字符。我下面的正则表达式适用于下面的 match1 等情况,但它也会匹配不在 ## 模式中的 # 或 ,如下面的 match2 所示,并因此失败。如果下面的正则表达式一起出现,如何修复它们以匹配 #*#?

var string1 = 'Hello#*#World#*#Some other string#*#false'
var string2 = 'Hello#*#World#*#Some #other #string#*#false'
// This would match
var match1 = string1.match(/^([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)$/);  
// This would no longer match since it matches other #'s that are not in a #*# pattern
var match2 = string2.match(/^([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)$/);

此外,匹配应该匹配模式之间的整个单词。所以对于 match1 来说就是

[ 'Hello#*#World#*#Some other string#*#false',
  'Hello',
  'World',
  'Some other string',
  'false',
  index: 0,
  input: 'Hello#*#World#*#Some other string#*#false',
  groups: undefined ]

最佳答案

你可以试试这个。

var string1 = 'Hello#*#World#*#Some other string#*#false'
var string2 = 'Hello#*#World#*#Some #other #string#*#false'
// This would match
var match1 = string1.match(/[^(#\*#)]+/g);  

var match2 = string2.match(/[^(#\*#)]+/g);

console.log(match1);
console.log(match2);

关于javascript - 正则表达式匹配除字符组合之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638756/

相关文章:

javascript - 与单元格宽度不同的 HTML 表格标题

javascript - 访问对象数组中的项目

javascript通过使用正则表达式匹配键从JSON对象中检索值

regex - Putty命令查找非罗马字母命名的文件

arrays - 仅提取谷歌表格中每个单元格的第一行

javascript - 在 Jupyter/iPython notebook 中以图形方式选择几何对象

javascript - 当使用 ajax 调用渲染表单时,客户端验证在 Yii2 中不起作用

r - 排除某个字符串第二次出现后的所有内容

regex - sed regex - 当行中出现模式时匹配两个双引号之间的文本

javascript - 通过使用 jQuery 重新排序元素来模拟 CSS Column 垂直内容流?