Search code examples
javaregexmatchingregex-group

regex match getting wrong in group 1


I have a string and I need this pattern $body.anyname or $body.anyname.anyname or like this, but not like $body.anyname. I wrote this regex \$[body](\w+((\[\d\]){0,}\.\w+(\[\d\]){0,}){0,}) its matching the whole string but I need the body.anyname in group 1, but getting ody.anyname This can be done by string manipulation but for some reason I need to use regex. Check the regex here https://regex101.com/r/PigNVO/1/


Solution

  • You could use and assertion for a whitespace boundary at the right to exclude the dot.

    Note that this part [body] is character class that matches either b o d or y and is not part of the first group.

    \$(body(?:\.\w+)+)(?!\S)
    

    In parts

    • \$ Match $
    • ( Capture group 1
    • body Match literally
      • (?:\.\w+)+ Repeat 1+ times matching a dot and 1+ word chars
    • ) Close group 1
    • (?!\S) Assert a whitespace boundary to the right

    Regex demo