简体   繁体   中英

Searching characters with regular expressions

How do I search a string that can have a "<=", ">=" or a "="?

I´ve reached this point:

[<>][=] 

so it searches the first two

Is there any character that inside the [<>] searches "nothing" so i will just get the [=] that follows?

To make some pattern optional, one or zero occurrences, use ? quantifier:

[<>]?=

In Java, you can use it with matches() to check if a string contains <= , >= or just = :

if (s.matches("(?s).*[<>]?=.*")) {...}

Or using a Matcher#find() ( demo ):

String s = "Some = equal sign";
Pattern pattern = Pattern.compile("[<>]?=");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println("Found " + matcher.group()); 
} // => Found =

An alternative to @stribizhev's suggestion to use ? is to explicitly enumerate the three cases:

(<=|>=|=)

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