splay
splay

Reputation: 327

Regex pattern to match only two characters between commas in Java

so for example in this string "3F, 4B, AA, A4B" I want a regex pattern that would be able to capture 3F, 4B, and AA. The amount of characters between the commas has to be 2. The only exception is that if both the characters are numbers we don't want to accept. We also do not care about white space.

Upvotes: 2

Views: 2666

Answers (2)

Saleem
Saleem

Reputation: 8978

Try following regex:

\b(\d[a-z]|[a-z]\d|[a-z]{2})(?=\b)

This will capture only two letter composed of either alpha numeric or alpha only.

See demo at Regex101

Upvotes: 0

anubhava
anubhava

Reputation: 784908

You can use this lookahead regex:

\b([a-zA-Z][a-zA-Z\d]|\d[a-zA-Z])(?=\s*,)
  • \b is for word boundary.
  • positive lookahead, (?=\s*,) to assert there there is following , after 2 characters.
  • ([a-zA-Z][a-zA-Z\d]|\d[a-zA-Z]) to ensure we use at least one alphabet in 2 characters

in Java:

Pattern p = Pattern.compile("\\b([a-zA-Z][a-zA-Z\\d]|\\d[a-zA-Z])(?=\\s*,)");

RegEx Demo

Upvotes: 2

Related Questions