【问题标题】:is there a regex expression to replace this if condition是否有一个正则表达式来替换这个 if 条件
【发布时间】:2021-11-21 14:56:41
【问题描述】:

我有三个字符串,我需要检查其中一个是否包含与给定顺序相同的另外两个,现在我正在使用很多条件来实现这一点,有没有办法使用正则表达式来简化它?

代码如下:

var a = '**';
var b = '##';
var phrase = '**Lorem ipsum dolor sit amet##';

if(phrase.includes(a) && phrase.includes(b) && (phrase.indexOf(a) < phrase.indexOf(b))) {
  // add logic
}

【问题讨论】:

标签: javascript regex conditional-statements indexof


【解决方案1】:

你可以在##之前使用一个模式来匹配**

^(?:(?!##|\*\*).)*\*\*.*##
  • ^ 字符串开始
  • (?:(?!##|\*\*).)* 匹配任何字符,但不直接跟在 ##** 后面
  • \*\*第一场比赛**
  • .* 匹配任意字符 0+ 次
  • ##匹配##

Regex demo

var phrase = '**Lorem ipsum dolor sit amet##';

if (phrase.match(/^(?:(?!##|\*\*).)*\*\*.*##/)) {
  // add logic
}

var phrases = [
  '**Lorem ipsum dolor sit amet##',
  'test****#**##',
  '##**Lorem ipsum dolor sit amet##',
  '##**##**',
];
phrases.forEach(phrase => {
  if (phrase.match(/^(?:(?!##|\*\*).)*\*\*.*##/)) {
    console.log(`Match for ${phrase}`);
  } else {
    console.log(`No match for ${phrase}`);
  }
});

【讨论】:

  • 更简单的/\*\*.+?##/怎么样?
  • @evolutionxbox 因为更简单的东西在这里给出了误报regex101.com/r/IO4n0u/1
  • @Thefourthbird 谢谢我正在寻找的东西
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
相关资源
最近更新 更多