Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check if a pattern exists in a String

Tags:

java

regex

I tried searching but could not find anything that made any sense to me! I am noob at regex :)

Trying to see if a particular word "some_text" exists in another string.

String s = "This is a test() function"
String s2 = "This is a test    () function"

Assuming the above two strings I can search this using the following pattern at RegEx Tool

[^\w]test[ ]*[(]

But unable to get a positive match in Java using

System.out.println(s.matches("[^\\w]test[ ]*[(]");

I have tried with double \ and even four \\ as escape characters but nothing really works.

The requirement is to see the word starts with space or is the first word of a line and has an open bracket "(" after that particular word, so that all these "test (), test() or test ()" should get a positive match.

Using Java 1.8

Cheers, Faisal.

like image 954
Faisal Avatar asked Dec 14 '22 09:12

Faisal


2 Answers

The point you are missing is that Java matches() puts a ^ at the start and a $ at the end of the Regex for you. So your expression actually is seen as:

^[^\w]test[ ]*[(]$

which is never going to match your input.

Going from your requirement description, I suggest reworking your regex expression to something like this (assuming by "particular word" you meant test):

(?:.*)(?<=\s)(test(?:\s+)?\()(?:.*)

See the regex at work here.

Explanation:

^                 Start of line - added by matches()
(?:.*)            Non-capturing group - match anything before the word, but dont capture into a group
(?<=\s)           Positive lookbehind - match if word preceded by space, but dont match the space
(                 Capturing group $1
  test(?:\s+)?    Match word test and any following spaces, if they exist
  \(              Match opening bracket
)                 
(?:.*)            Non-capturing group - match rest of string, but dont capture in group
$                 End of line - added by matches()

Code sample:

public class Main {
    public static void main(String[] args) {
        String s = "This is a test() function";
        String s2 = "This is a test    () function";
        System.out.println(s.matches("(?:.*)((?<=\\s))(test(?:\\s+)?\\()(?:.*)")); 
        //true
    }
}
like image 190
vs97 Avatar answered Jan 03 '23 08:01

vs97


I believe this should be enough:

s.find("\\btest\\s*\\(")
like image 27
Óscar López Avatar answered Jan 03 '23 09:01

Óscar López