Regex to match whole words that begin with $

后端 未结 6 1758
心在旅途
心在旅途 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 18:53

    Try this as your regex:

    / (\$\w+)/
    

    \w+ means "one or more word characters". This matches anything beginning with $ followed by word characters, but only if it's preceded by a space.

    You could test it with perl (the \ after the echo is just to break the long line):

    > echo 'abc $def $ ghi $$jkl mnop' \
      | perl -ne 'while (/ (\$\w+)/g) {print "$1\n";} ' 
    $def
    

    If you don't use the space in the regex, you'll match the $jkl in $$jkl - not sure if that is what you want:

    > echo 'abc $def $ ghi $$jkl mnop' \
      | perl -ne 'while (/(\$\w+)/g) {print "$1\n";} ' 
    $def
    $jkl
    
    0 讨论(0)
  • 2021-01-01 18:54

    This should be self-explanatory:

    \$\p{Alphabetic}[\p{Alphabetic}\p{Dash}\p{Quotation_Mark}]*(?<!\p{Dash})
    

    Notice it doesn’t try to match digits or underscores are other silly things that words don’t have in them.

    0 讨论(0)
  • 2021-01-01 19:01

    If you want to match only whole words, you need the word character selector

    \B\$\w+
    

    This will match a $ followed by one or more letters, numbers or underscore. Try it out on Rubular

    0 讨论(0)
  • 2021-01-01 19:05

    For the testing part of you question I can recommend you using http://myregexp.com/

    0 讨论(0)
  • 2021-01-01 19:07
    \$(\w+) 
    

    Explanation :

    \$ : escape the special $ character
    () : capture matches in here (in most engines at least)
    \w : match a - z, A - Z and 0 - 9 (and_)
    + : match it any number of times

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题