1

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'

Nursd
  • 21
  • 4
  • Nothing to do with alternation (the "OR") - your first pattern is unbounded, so it matches any alphanumeric in any place. Moreover, it only expects one character. – VLAZ May 13 '22 at 09:35
  • How to bound it to meet the requirements ? – Nursd May 13 '22 at 09:55
  • [How do I match an entire string with a regex?](https://stackoverflow.com/q/4123455) | [Difference between matches() and find() in Java Regex](https://stackoverflow.com/q/4450045) | [Regex for checking if a string is strictly alphanumeric](https://stackoverflow.com/q/11241690) – VLAZ May 13 '22 at 10:16
  • You're missing a + on the first part: `[a-zA-Z0-9]+`, which will tell you the regex to accept one **or more** alphanumeric characters. – lemon May 13 '22 at 10:17

1 Answers1

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.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22