1

I want to find a function in java that can check if string contain pattern "%A%B%" just like 'LIKE' statement in SQL. This function will return true if the string contain the pattern and false if not.

Can anyone suggest any class, function or line of code? Thank you!

3
  • 2
    Regular expressions? Commented Sep 15, 2015 at 6:33
  • 3
    Regular expression: put .* instead of % and . instead of _ Commented Sep 15, 2015 at 6:36
  • What do '.' and '*' mean? Commented Sep 15, 2015 at 6:54

2 Answers 2

1

Regular expression. Learn more here: https://docs.oracle.com/javase/tutorial/essential/regex/

The easiest way of calling it is using String.matches(String regex)

If you want to check the same regular expression more often, it's better to precompile it and use a Pattern.

A typical invocation sequence is then

 Pattern p = Pattern.compile(".*A.*B.*"); // you keep this stored for re-use
 Matcher m = p.matcher("BARBARIAN");
 boolean b = m.matches();

There is a good Online Regex Tester and Debugger tool, where you can check your regular expression.

Sign up to request clarification or add additional context in comments.

1 Comment

The regex suggested here doesn't match the same things as LIKE "%A%B%". For example, it won't match "BARBARIAN", whereas the SQL expression would.
1
Pattern.compile(".*A.*B.*").matches(input)

will return true if input contains an A followed by a B.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.