简体   繁体   中英

How to use OR in a regex expression for Java?

I want to accept this both cases, I_LOVE_TO_CODE.txt or I_LOVE_TO_CODE_20151125.txt . I know how to do for each one of them separately:

^I_LOVE_TO_CODE.txt$
^I_LOVE_TO_CODE_\d{8}\.txt$

But how can I insert an OR condition in one single regex ?

In this case, you do not need an | ( OR ) operator because it would be an inefficient solution. The ^I_LOVE_TO_CODE_\\d{8}\\.txt$|^I_LOVE_TO_CODE\\.txt$ involves much backtracking. You could contract it to ^(I_LOVE_TO_CODE_\\d{8}\\.txt|I_LOVE_TO_CODE\\.txt)$ (where anchors apply to both subexpressions but are used once), or ^I_LOVE_TO_CODE(_\\d{8}\\.txt|)$ - which is already much better, but alternation can be avoided here altogether using optional grouping .

Use an optional group here like this:

^I_LOVE_TO_CODE(?:_\d{8})?\.txt$
               ^^^      ^^ 

See regex demo

The (?:_\\d{8})? means match an underscore followed with 8 digits one or zero times, but do not capture the substring . Unless you need to use the value, you can do without a capturing ( (_\\d{8})?) group.

More details on alternation operator and optional items is available at Regular-Expressions.info .

In the specific case of the patterns you are trying to match here, where one pattern is the same as the other, just with "a bit added in the middle", you can use an optional group, as stribizhev suggests.

If you are trying to match either of two (or more) things in general, you can use the | operator, as described in the Pattern javadoc :

"^(?:foo|bar|baz)$"

would match either "foo" , "bar" or "baz" .

I don't understand exactly your question. In regular expressions you can use | to determine the value before the | or the value after.

You can save both in different vars like:

String var01= "your route to the .txt file";
String var02= "your route to the .txt file";
String regex= "your regex";

Afterwards, you can use an if statement like:

if((var01||var02).matches(regex)) {
    System.out.println("Succes!");
}
else {
    System.out.println("Validation failed!");
}

Note that .matches returns a true boolean if the validation has been matched succesfully.

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