组合Regex来匹配字符串的变体

Combine Regex to match variations of a String

本文关键字:字符串 Regex 组合      更新时间:2023-09-26

我有一个字符串,我想从使用javascript拉一些内容。该字符串可以有多种形式,如下所示:

[[(a*, b*) within 20]] or [[...(a*, b*) within 20]],其中"…"可能存在,也可能不存在。

我想要一个匹配"(a*, b*)在20"部分的正则表达式。

/'['[(.*?)']']/.exec(text)[1]将匹配[[(a*, b*) within 20]]

/([^'.]+)']']/.exec(text)[1]将匹配[[...(a*, b*) within 20]]

我如何结合这些,使两个版本的文本将匹配"(a*, b*)在20"?

你可以使用这个正则表达式:

var m = s.match(/'['[.*?('([^)]*').*?)']']/);
if (m)
    console.log(m[1]);
    // (a*, b*) within 20 for both input strings

我想要一个匹配(a*, b*) within 20部分的正则表达式。

你可以试试

'['[.*?('(a'*, b'*') .*?)']']

下面是regex101

的演示

注意:您可以使用'w[a-z],使其更精确,根据您的需要,而不是ab

'['[.*?('w'*, 'w'*') .*?)']']

转义字符'用于转义regex模式中的特殊字符,如。[[]] * ()

您可以使用以下命令来匹配这两个变量。

'['[[^(]*('([^)]*')[^']]*)']']

:

'[            #   '['
'[            #   '['
[^(]*         #   any character except: '(' (0 or more times)
(             #   group and capture to '1:
  '(          #     '('
  [^)]*       #      any character except: ')' (0 or more times)
  ')          #     ')'
  [^']]*      #     any character except: '']' (0 or more  times)
)             #   end of '1
']            #   ']'
']            #   ']'
演示工作