I am trying to create a regex that will capture string between the square brackets, and if there is a number like (1234) then that should be excluded
I am using the regex
\[(.*?)\]
Suppose the sample data is
requests[45180], indices[movies]
In this case, I get the output as :
[45180]
[movies]
But my expected output is :
movies
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatcher {
private static String REGEX = "\\[(.*?)\\]";
private static String NUMBERS_REGEX = "\\d+";
private static List sampleData = Arrays.asList("test from [a.b.v1.2.0.71-0] to [a.b.v1.2.0.73-0]",
"requests[45180], indices[movies]");
public static void main(String[] args) {
Pattern pattern = Pattern.compile(REGEX);
Pattern numberPattern = Pattern.compile(NUMBERS_REGEX);
for (Object data : sampleData) {
List<String> indices = new ArrayList<>();
Matcher matcher = pattern.matcher(data.toString());
while (matcher.find()) {
String index = matcher.group().replaceAll("[\\[\\]']+", "");
Matcher numberMatcher = numberPattern.matcher(index);
if (!numberMatcher.matches())
indices.add(index);
}
if (indices.size() > 0)
System.out.println("Indices: " + indices);
}
}
}
Can anyone please help me resolve this issue?