In SQL, we have pattern matching operator like
with "_
" and "%
" to search for a string, or a part of a string.
Is there anything similar to that in Java.
There is the matches()
method. However, that only returns true
if the entire String
matches the regex.
I need a method that can evaluate if a given String
exists in another String
as a part of it.
Asked
Active
Viewed 2,245 times
0

shA.t
- 16,580
- 5
- 54
- 111

Valli Pichappan
- 21
- 5
-
2`"_" and "%` are not `pattern matching operators`. That are wildcards – Jens Aug 30 '17 at 13:20
-
1dear , you want `contains` – Pavneet_Singh Aug 30 '17 at 13:21
-
2*only returns true if the entire string matches the regex* No. It Returns true if the string mataches the regex. you can use dot for every character. Something like `.*HELLO World.*` will match also `HELLO World i am here` – Jens Aug 30 '17 at 13:21
-
@Jens it is worth mentioning that by default `.` doesn't match line terminators so this will not work with multi-line text. To solve this problem we can use DOTALL flag (we can place `(?s)` at start of regex), or instead of `.` use sum of set and its negation like `[\s\S]` to represent all characters. – Pshemo Aug 30 '17 at 13:26
-
Possible duplicate of [How to implement a SQL like 'LIKE' operator in java?](https://stackoverflow.com/questions/898405/how-to-implement-a-sql-like-like-operator-in-java) – shA.t Aug 30 '17 at 13:28
3 Answers
2
Check the contains method of the String class:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

Norbert
- 1,391
- 1
- 8
- 18
1
contains is not usable if you need to perform regex matching.
You can trick the matches() method to behave as you expect, just saying that you want whatever sequence of character at start and end of the string.
Nice solution is to use matcher.find() which looks for occurrences of the regex. Look at class Matcher.

Nicola Pellicanò
- 469
- 2
- 5
0
You can use String.Contains()
Example:
public static void main(String[] args)
{
String s = "Hello World";
System.out.print(s.contains("Wor")); //return true
System.out.print(s.contains("wor")); //return false beacuse is case-sensitive
}

Giuseppe Vitale
- 1
- 1