开发者

How can I match a pattern in regex that can contain anything (letters,numbers,...) but match only if it contains an underscore?

开发者 https://www.devze.com 2022-12-25 06:16 出处:网络
How can I match a pattern in regex that can contain anything (letters,numbers,...) but matches only if it contains an un开发者_开发技巧derscore?

How can I match a pattern in regex that can contain anything (letters,numbers,...) but matches only if it contains an un开发者_开发技巧derscore?

Basically I want to match bob_hello but not bobhello.


This seems pretty much like a homework question, so I'm not going to just give you the answer.

But, what you need to do is this:

Write a three part regular expression:

  1. First match any sequence of characters from the start of the string except '_'
  2. Then match exactly '_'
  3. Then match anything else, to the end of the string

There are other ways, of course - but this will work.


If you want to match everything, ^.*_.*$ will do it. If you just want to test if the string contains a _, _ will be enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号