import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?<!\\d,)(?<!\\d)\\d{1,3}(?:,\\d{3})*(?!,?\\d)";
final String string = "I need help finding a regex rule that should search in a large string/text and match numbers that have the format: 12,345,678 or 1,234,567 or 12,345 or 1,234.\n\n"
+ "for example: for 12,345,678 it should match 12,345,678 and not 345,678 or 45,678 or anything similar\n\n"
+ "I looked in: Regex help needed to match numbers but the answers either match 1 in 1,23,456 (should not at all because 1,23,456 is not a number) or match 23,456 in 12,23,456 (should not match at all)\n\n"
+ "In creating a regex rule to match the correct format number, I tried first creating the rule of what it should not match(i.e., not 1,23,456), then I tried creating the rule of what it should match. The last rule I created matches in most cases, but not in all.\n\n"
+ "MATCH:\n\n"
+ "1 12 123 1,234 12,345 123,456 1,234,567 12,\n\n"
+ "NO MATCH:\n\n"
+ "1,24,567 1,234,5 1,2 1,2,567 12567 ";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html