using regex g flag in java
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
Related videos on Youtube
Comments
-
Sandeep Chauhan over 1 year
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.
-
PshemoI wouldn't say it is not about specific regex since Java has global flag set on by default (what is more, you can't even turn it off). But if you are not able to match something properly, then problem most likely lies in pattern. In your case possible cause could be
.*
which by default is greedy so it attempts to match as much text as possible, which based on data from your link looks like matching all methods as one match (likestart of first method{ .* end of last method}
). Possible solution for that could be making.*
reluctant with.*?
.
-