简体   繁体   中英

how to strictly find substring of string in java?

I want to find particular string in JAVA and I am using CONTAINS function for that.

But problem with CONTAINS is that it gives true even if there is a super string available for that string.

Ex- let's say

String i = "anand > 5 or id < 6" 

and I want to check whether string contains AND or OR. But here i.contains("and") will give true because of anand.

How to solve this issue?

Is there any function available in library?

if (i.matches("(?s).*\\b(and|or)\\b.*")) System.println("AND or OR found");

(?s) let . also match newlines \\\\b is a word boundary


In answer to comment "hey now I wanted..."

String[] words = ...;
StringBuilder expr = new StringBuilder();
for (String word : words) {
    if (expr.length() != 0)
        expr.append("|"):
    expr.append(word);
}
i = i.replaceAll("\\b(" + expr + ")\\b", "bla");

You might want to take a look at regular expressions and use the following regex:

"\\band\\b"

The \\\\b should denote the regex to match whole words only.

You want to check whether your string contains AND or OR then it is wrong to check i.contains("and") you should use contains method with case sensitive. to check whether string contains AND you need to write contains("AND")

String i = "anand > 5 or id < 6";
        System.out.println(i.contains("AND"));//returns false

        System.out.println(i.contains("and"));//returns true

because the string contains and not AND it is case sensitive

看起来您想检查“ AND”(带空格),而不是“ AND”

我会这样:-用大写字母搜索要搜索的字符串(以避免或/或和/与问题)-搜索“和”(即前导和尾随空格)

Looks you want regular expressions where you surround the word you are looking for with word breaks, ie

"\\bAND\\b"

This will match AND only when it is not surrounded by other letters.

You want whole word search. It could be done with regexps:

i.matches("\\band\\b")

where \\b stands for word boundary

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