简体   繁体   中英

Regex to match exact substring java

I have a string as below

TestFilter('value') AND LoadTestFilter('value1') AND UserFilter(value2) OR TestFilter('value3')

I want to extract only TestFilter along with brackets from the above string. I want regex to match only these two substrings

 TestFilter('value')
 TestFilter('value3')

I have tried below regex

.*TestFilter\\((.*?)\\).*

It is working but it is also matching LoadTestFilter in the string

How to match only TestFilter.

    String s = "TestFilter('value') AND LoadTestFilter('value1') AND UserFilter(value2) OR TestFilter('value3')";
    Matcher m = Pattern.compile("\\bTestFilter\\(.*?\\)").matcher(s);
    while (m.find()) {
        System.out.println(m.group(0));
    }

Explanation:

The key thing here is \\b , which matches a word boundary . \\b in the regex I used matches a word boundary at the very start of the match, and before TestFilter . Translating to a less regex-like language, we don't want any letters before TestFilter .

According to your comment, you see to have tried .*\\bTestFlter\\(.*?\\) . This does not work because of the .* at the front. You're basically matching a bunch of random characters, followed by a word boundary, "TestFilter" then a pair of brackets with random stuff in it. This will match the whole string, since the last instance of TestFilter is preceded by a word boundary, then a bunch of random characters.

Try this:

TestFilter\\((.*?)\\).*

without first (.*)

\\b matches a word boundary in regex expressions. So \\bTestFilter will match "TestFilter" but not "LoadTestFilter" , because there is no word boundary between "Load" and "Test" .

Thus, you could use:

\\bTestFilter\\((.*?)\\)

or

.*\\bTestFilter\\((.*?)\\).*

depending on how you are matching the input (eg, match() -vs- find() )


Matcher#find example:

String haystack = "TestFilter('value') AND LoadTestFilter('value1') AND UserFilter(value2) OR TestFilter('value3')";
Matcher needle = Pattern.compile("\\bTestFilter\\((.*?)\\)").matcher(haystack);

while(needle.find()) {
    System.out.format("[%s] found in [%s]%n", needle.group(1), needle.group());
}

Output:

['value'] found in [TestFilter('value')]
['value3'] found in [TestFilter('value3')]

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