简体   繁体   中英

Optional group not working in regex

I have the following strings:

"What version is installed on production server?"
"What appserver version is installed on production server?"
"What system version is installed on production server?"
"What os version is installed on production server?"

And the following regex:

 /(?:what|which).*(appserver|system)?.*version.*\son\s(\w*).*/i

I would expect to get appserver or system or undefined as the first matching group but I always get undefined .

If I remove the ? from the first matching group, I get appserver and system but the first and last string does not match anymore.

What is wrong?

See http://jsfiddle.net/ZVQTb/5/ for test bench.

The problem is that you're trying to look for anything up to "appserver" or "system", but when it's not there, there isn't another group before "version".

/(?:what|which).+?(appserver|system)?.*version.*\son\s(\w*).*/i

FIDDLE

Note: changed + to +? per Evan's keen eyes.

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