简体   繁体   中英

Regular expression for multiple words with * and space

My regular expression is of format "Exit* Order*". When i use in java its not working as expected.

String pattern = "Exit* Order*";
String ipLine = "Exiting orders";

Match: NO

String pattern = "Exit Order";
String ipLine = "Exit order";

Match: Yes.

Java Code: Pattern patrn = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); Matcher match = patrn.matcher(ipLine);

Can any one let me know what should be the pattern in such cases.

I believe you are looking for something like:

"Exit.* Order.*"

or maybe something instead of .* , eg \\S* , \\w* , [A-Za-z]* .

Your current regular expression is looking for zero or more t and r on the ends of the words, eg it would match

Exi Orde
Exit Orde
Exitt Orde
Exi Order
Exi Orderr
...
Exit\\w* Order\\w*

You should use this. .* can match much more than intended.use i or ignorecase flag

It seems like you just want to match "Exit Order" case-insensitively:

Try this:

if (str.matches("(?i)exit order"))

Or to restrict the match to just your examples, where the "O" of "Order may be "o", use:

if (str.matches("Exit [Oo]rder"))

Java does not use Linux regexp expression: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Use this:

String pattern = "Exit.* Order.*";

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