简体   繁体   中英

Regular expression for this?

How can I make a RegEx that matches something like these?

"Hi hello world" and "Hi world"

I tried

/^Hi (hello)? world$/i

But it doesn't work.

/^Hi( hello)? world$/i

The space before hello (or the one after) also needs to be optional, otherwise it matches either:

  • hi__world (the underscores are "spaces")
  • hi hello world

应该这样做:

 /^Hi( | hello )world$/i

试试/^Hi (hello )?world$/i ,您的代码仅匹配“ Hi hello world”和“ Hi world”

Hi (\hello |)world

The pipe character works as "or." So, the expression inside the parens matches either " hello" or nothing. You can test your Javascript regulare expressions here: http://rejex.heroku.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM