0

我想匹配字符串中除#*# 模式之外的所有字符。我在下面的正则表达式适用于下面的 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 ]
4

1 回答 1

1

你可以试试这个。

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);

于 2018-12-05T18:43:54.517 回答