简体   繁体   English

使用正则表达式搜索字符

[英]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? [<>]内是否有任何字符搜索为“ nothing”,所以我只得到后面的[=]?

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 = : 在Java中,可以将其与matches()一起使用,以检查字符串是否包含<=>=或just =

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

Or using a Matcher#find() ( demo ): 或使用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 ? @stribizhev建议使用的替代方法? is to explicitly enumerate the three cases: 明确列举三种情况:

(<=|>=|=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM