0

我想将多行中的特定模式与 Integromat 中的匹配模式进行匹配。语言是 ECMAScript (JavaScript) FLAVOR。

Salutation: Mr. x Mx. Mrs.

或者看起来像这样:

Salutation: Mr. Mx. x Mrs.

我想在 之后获取字符串x\s,以提取Mr. Mx.Mrs.

目前,我在这一点上,但它只有在 x 之前才匹配Mr.

Salutation:\s(x\s(.*?)[\s])

我需要如何更改它?提前致谢!

4

1 回答 1

0

You might use a capture group with an alternation to match either a single occurrence of Mr. Mrs. or Mx.

\bSalutation:.*?\sx\s(M(?:rs?|x)\.)

The pattern matches:

  • \bSalutation: Match literally
  • .*?\sx\s Match any char as least as possible till the first occurrence of x between whitespace chars
  • ( Capture group 1 (in the example referred to as m[1])
    • M(?:rs?|x)\. Match M followed by either r with optional s or x and then a dot
  • ) Close group 1

Regex demo

const regex = /\bSalutation:.*?\sx\s(M(?:rs?|x)\.)/;
[
  "Salutation: Mr. x Mx. Mrs.",
  "Salutation: Mr. Mx. x Mrs.",
  "Salutation: Mr. Mx. x Mr.",
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    console.log(m[1]);
  }
});


If you want to match all of the occurrences after the x, and a lookbehind is supported in the Javascript version:

(?<=\bSalutation:.*\sx\s.*)\bM(?:rs?|x)\.

Regex demo

于 2021-03-18T15:28:48.847 回答