Regex to match whole words that begin with $

后端 未结 6 1811
心在旅途
心在旅途 2021-01-01 18:14

I need a regex to match whole words that begin with $. What is the expression, and how can it be tested?

Example:

This $word and $this should

6条回答
  •  耶瑟儿~
    2021-01-01 19:08

    I think you want something like this:

    /(^\$|(?<=\s)\$\w+)/
    

    The first parentheses just captures your result.

    ^\$ matches the beginning of your entire string followed by a dollar sign;

    | gives you a choice OR;

    (?<=\s)\$ is a positive look behind that checks if there's a dollar sign \$ with a space \s behind it.

    Finally, (to recap) if we have a string that begins with a $ or a $ is preceded by a space, then the regex checks to see if one or more word characters follow - \w+.

    This would match:

    $test one two three
    

    and

    one two three $test one two three
    

    but not

    one two three$test
    

提交回复
热议问题