Regex word boundary expressions

前端 未结 4 418
时光说笑
时光说笑 2020-11-28 11:44

Say for example I have the following string \"one two(three) (three) four five\" and I want to replace \"(three)\" with \"(four)\" but

4条回答
  •  暖寄归人
    2020-11-28 12:31

    I recently came across a similar issue in javascript trying to match terms with a leading '$' character only as separate words, e.g. if $hot = 'FUZZ', then:

    "some $hot $hotel bird$hot pellets" ---> "some FUZZ $hotel bird$hot pellets"
    

    The regex /\b\$hot\b/g (my first guess) did not work for the same reason the parens did not match in the original question — as non word characters, there is no word/non-word boundary preceding them with whitespace or a string start.

    However the regex /\B\$hot\b/g does match, which shows that the positions not marked in @timwi's excellent example match the \B term. This was not intuitive to me because ") (" is not made of regex word characters. But I guess since \B is an inversion of the \b class, it doesn't have to be word characters, it just has to be not- not- word characters :)

提交回复
热议问题