Javascript Regex for all words not between certain characters

后端 未结 3 1761
借酒劲吻你
借酒劲吻你 2021-01-17 04:44

I\'m trying to return a count of all words NOT between square brackets. So given ..

[don\'t match these words] but do match these

I get a c

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 05:17

    Chris, resurrecting this question because it had a simple solution that wasn't mentioned. (Found your question while doing some research for a general question about how to exclude patterns in regex.)

    Here's our simple regex (see it at work on regex101, looking at the Group captures in the bottom right panel):

    \[[^\]]*\]|(\b\w+\b)
    

    The left side of the alternation matches complete [bracketed groups]. We will ignore these matches. The right side matches and captures words to Group 1, and we know they are the right words because they were not matched by the expression on the left.

    This program shows how to use the regex (see the count result in the online demo):

    
    

    Reference

    How to match (or replace) a pattern except in situations s1, s2, s3...

提交回复
热议问题