'Seems RegEx's 'OR' operator does not work

I have a pattern of regex that should match input that way:

Work -> correct

{"name": "name"} -> correct (any correct json format object)

War And Piece -> incorrect

Expression: "[a-zA-Z0-9]|^\{(\s*\"[a-zA-Z]+\w*\"\s*:\s*\"?\w+\.*\d*\"?\s*)}$"

but first part of expression does not work. It accepts {"name": "name"}, but does not accept 'Work'



Solution 1:[1]

For me, it's really hard to determine exactly what your trying to parse out and what you are parsing from. I gathered it's a json something or another which makes me wonder why you're not using a json parser.

In any case perhaps try this slightly modified regex with Pattern/Matcher and pull out group(0) (full matches) with matcher.find(), for example:

String regex = "\\b[a-zA-Z0-9]+\\b|^\\{(\\s*\\\"[a-zA-Z]+\\w*\\\"\\s*:\\s*\\\"?\\w+\\.*\\d*\\\"?\\s*)\\}$";
String string = "Work\n"
              + "{\"name\": \"name\"}\n"
              + "War And Piece";
    
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));
}

When run I get the following within the console Window:

Full match: Work
Full match: {"name": "name"}
Full match: War
Full match: And
Full match: Piece

If this is not what you are looking for then I'll just delete this post.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DevilsHnd