且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果捕获组匹配字符串,则为正则表达式

更新时间:2022-05-29 00:57:31

您可以将异常编码为一种模式,以在元音之后检查并停止匹配,或者您仍然可以在另一个元音之前使用任何其他辅音,并且用连字符替换整个匹配的反向引用:

You may code your exceptions as a pattern to check for after a vowel, and stop matching there, or you may still consume any other consonant before another vowel, and replace with the backreference to the whole match with a hyphen right after:

.replace(/[aeiou](?:(?=[bcdfghptv][lr])|[bcdfghj-nprstvwxy](?=[bcdfghj-nprstvwxy][aeiou]))/g, '$&-')

如果需要不区分大小写的匹配,请在 g 后添加 i 修饰符.

Add i modifier after g if you need case insensitive matching.

请参阅正则表达式演示.

详情

  • [aeiou] - 元音
  • (?: - 非捕获组的开始:
    • (?=[bcdfghptv][lr]) - 正向前瞻,要求异常字母簇立即出现在当前位置的右侧
    • | - 或
    • [bcdfghj-nprstvwxy] - 辅音
    • (?=[bcdfghj-nprstvwxy][aeiou]) - 后跟任何辅音和元音
    • [aeiou] - a vowel
    • (?: - start of a non-capturing group:
      • (?=[bcdfghptv][lr]) - a positive lookahead that requires the exception letter clusters to appear immediately to the right of the current position
      • | - or
      • [bcdfghj-nprstvwxy] - a consonant
      • (?=[bcdfghj-nprstvwxy][aeiou]) - followed with any consonant and a vowel

      替换模式中的 $& 是整个匹配值的占位符(在 regex101,$0 只能在此时使用,因为网站不支持仅特定于语言的替换模式).

      The $& in the replacement pattern is the placeholder for the whole match value (at regex101, $0 can only be used at this moment, since the Web site does not support language specific only replacement patterns).