【问题标题】:detect specific strings with or without spaces in between in Regex检测正则表达式之间有或没有空格的特定字符串
【发布时间】:2019-08-25 17:04:23
【问题描述】:

我想编写一个 javascript 正则表达式来检测 3 个特定的字符集:

  1. 字符串“类名”
  2. 字符“=”
  3. 字符“{”

我想检测这些带或不带空格的 - 这意味着它应该适用于所有这些字符串:

'className={}'
'className ={}'
'className= {'
'className = {}'

我们如何检测正则表达式中带有或不带有空格的特定精确字符组??

【问题讨论】:

  • /^className\s*=\s*{/你可以试试这个
  • 非常感谢 - 它有效 - 适当地注意到 * 字符的使用!太棒了!
  • 我也忘了提到这种模式在其他东西中间的情况 - 所以我在开头删除了插入符号
  • 在这种情况下,您应该使用\b 字边界而不是插入符号。否则它也会检测到 helloclassName={ 之类的东西

标签: javascript regex string regex-group


【解决方案1】:

检查每个所需字符集之间的一个或多个空格:

const strings = ['className={}',
  'className ={}',
  'className= {',
  'className = {}'
];

const regex = /className\s*=\s*\{\}\s*/;
strings.forEach(str => console.log(regex.test(str)));

注意:第三个示例返回false,因为没有右大括号}

如果最后一个大括号是可选的:

const strings = ['className={}',
  'className ={}',
  'className= {',
  'className = {}'
];

const regex = /className\s*=\s*\{\}?\s*/;
strings.forEach(str => console.log(regex.test(str)));

【讨论】:

  • 谢谢 - 这行得通 - 实际上我不需要结尾花括号 -
  • 所以你希望最后一个大括号是可选的@Probosckie?
  • 是的 - 所以我使用 let classNameRegex = /className\s*=\s*{/;
猜你喜欢
  • 2017-10-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
相关资源
最近更新 更多