using regex g flag in java

Sandeep Chauhan picture Sandeep Chauhan · Aug 4, 2018 · Viewed 8.4k times · Source

Is it possible to use regex global g flag in java pattern ?

I tried with final Pattern pattern = Pattern.compile(regex,Pattern.DOTALL); but it do not behave like global flag.

Do we have any workaround for it in java ?

My Regex is :
private final String regex ="(public|private|protected|static|final|abstract|synchronized|volatile)\\s*([\\w<>\\[\\]]+)\\s*(\\w+)\\s*\\(([\\w\\s\\w,<>\\[\\]]*)?\\)\\s*(\\bthrows\\b)?[\\s\\w\\s,\\w]*\\{[\\n\\t]*(.+)[\\n\\t]*((return|throw){1}\\s*)(\\w*)\\s*;\\s*[\\}]";

input is the file content , something like mentioned in below regex link : https://regex101.com/r/u7vanR/3

I want java pattern to find both the occurrences, but with java regex flags its just finding the first one and not both.

Answer

zhh picture zhh · Aug 4, 2018

Java does not have global flag. You can get all matches via find and group.

Pattern pattern = Pattern.compile("1");
Matcher matcher = pattern.matcher("111");
while (matcher.find()) {
    System.out.println(matcher.group());
}

The output is

1
1
1