Javascript reg ex仅匹配整个单词,仅由空格绑定 [英] Javascript reg ex to match whole word only, bound only by whitespace

查看:118
本文介绍了Javascript reg ex仅匹配整个单词,仅由空格绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道\ bblah \ b将匹配整个Blah,但它也会匹配Blah的Blah.jpg我不想要它。我想只匹配整个单词和两边的空格。

so I know \bBlah\b will match a whole Blah, however it will also match Blah in "Blah.jpg" I don't want it to. I want to match only whole words with a space on either side.

推荐答案

你可以尝试: \\ \\ sBlah \s

或者,如果您允许开始和结束锚点,(^ | \ s) Blah(\ s | $)

Or if you allow beginning and end anchors, (^|\s)Blah(\s|$)

这将匹配Blah by本身,或每个 Blah in Blah and Blah

This will match "Blah" by itself, or each Blah in "Blah and Blah"


  • regular-expressions.info/Character classes Anchors


    • \s 代表空白字符。

    • 插入符 ^ 匹配字符串中第一个字符前的位置

    • 同样, $ 在字符串中的最后一个字符后面匹配

    • regular-expressions.info/Character classes and Anchors
      • \s stands for "whitespace character".
      • The caret ^ matches the position before the first character in the string
      • Similarly, $ matches right after the last character in the string

      如果你想在Blah Blah中匹配 Blah ,然后由于在两次出现之间共享一个空格,您必须使用断言。类似于:

      If you want to match both Blah in "Blah Blah", then since the one space is "shared" between the two occurrences, you must use assertions. Something like:

      (^|\s)Blah(?=\s|$)
      



      参见




      • regular-expressions.info/Lookarounds

      • See also

        • regular-expressions.info/Lookarounds
        • 上面的正则表达式也会匹配前导空格。

          The above regex would also match the leading whitespace.

          如果你只想要 Blah ,理想情况下,lookbehind将会很好:

          If you want only Blah, ideally, lookbehind would've been nice:

          (?<=^|\s)Blah(?=\s|$)
          

          但是由于Javascript不支持它,你可以改写:

          But since Javascript doesn't support it, you can instead write:

          (?:^|\s)(Blah)(?=\s|$)
          

          现在 Blah 将在 \1 中捕获,没有领先的空白。

          Now Blah would be captured in \1, with no leading whitespace.

          • regular-expressions.info/Grouping and flavor comparison

          这篇关于Javascript reg ex仅匹配整个单词,仅由空格绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆