import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\b[A-Z0-9]+(?:-[A-Z0-9]+)+";
final String string = "I only want the Uppercase Letters and Numbers with dashes, so it does get GC-113, AO-1-GC-113, AO-2-GC-113, which is great!\n\n"
+ "\"I don't want this ------, but this is good GC-113, AO-1-GC-113, AO-2-GC-113\"\n\n"
+ "BUT if I come across one where there is no space between the number, but just another character like a comma or a period then it returns a match on the entire section \"GC-113,AO-1-GC-113,AO-2-GC-113\"\n\n"
+ "\"I don't want this ------, but this is good GC-113,AO-1-GC-113,AO-2-GC-113\"";
final Pattern pattern = Pattern.compile(regex);
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