简体   繁体   中英

Java Regex to match a specific string or another specific string, or not at all?

Imagine capturing the input with a regex:

2.1_3_4
3.2.1
3.2.1.RELEASE
3.2.1.SNAPSHOT

The numbers and the dots are easy enough to get

([0-9\._]+)

But how do you capture that plus "RELEASE" or "SNAPHOT" or none of those?

I played around with the or operator to no avail...

([0-9\._]+RELEASE||SNAPSHOT)  // no worky

btw, this is a nice regex tester: http://java-regex-tester.appspot.com/

I think you want this:

([0-9._]+(RELEASE|SNAPSHOT)?)

The (inside) parens form a group, and the question mark indicates the group may occur 0 or 1 times.

You are doing great. You just need to make a few changes.
First, you do not use || for or, | is used. So RELEASE||SNAPSHOT would convert to RELEASE|SNAPSHOT .
Since release or snapshot is not mandatory, a ? should be placed after it. So the final regex becomes

([0-9\._]+(RELEASE|SNAPSHOT)?)

You can also use \\d instead of 0-9 . else than this, there is no need to escape . by \\ when its present inside []
So finally, following could be the final regex

([\d._]+(RELEASE|SNAPSHOT)?)

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