Regex: Use start of line/end of line signs (^ or $) in different context

后端 未结 3 518
遇见更好的自我
遇见更好的自我 2021-01-30 19:44

While doing some small regex task I came upon this problem. I have a string that is a list of tags that looks e.g like this:
foo,bar,qux,garp,wobble,thud

相关标签:
3条回答
  • 2021-01-30 20:05

    Just use look-arounds to solve this:

    (?<=^|,)garp(?=$|,)
    

    The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

    0 讨论(0)
  • 2021-01-30 20:07

    You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

    (^|,)garp(,|$)
    
    0 讨论(0)
  • 2021-01-30 20:25

    you just need to use word boundary (\b) instead of ^ and $:

    \bgarp\b
    
    0 讨论(0)
提交回复
热议问题