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.
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
}
}
I believe this should be enough:
s.find("\\btest\\s*\\(")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With