Megan
Megan

Reputation: 927

Regular expression Pattern matching java

I need to have a Regex for the string: Created ID @DBDOYEF has problems

The word @DBDOYEF may contain a-z,A-Z,0-9 and all special characters like

~!#$%^&*()_+{}:"<>?,./\.

Please help me to create a pattern for this word. I used

Created ID \\b[A-Z][0-9][\\//+-@#$%^~&*!():]+\\b has problems

for this, but it fails for many cases.

Upvotes: 2

Views: 451

Answers (2)

Mariano
Mariano

Reputation: 6521

it may or may not start with @. some times it starts with : or A-Z or a-z or 0-9

You were trying [A-Z][0-9][\\//+-@#$%^~&*!():]+, which requires 1 letter, followed by 1 digit, followed by any punctuation. Instead, use the same character class for all allowed characters.

Regex

Created ID [@A-Za-z0-9~!#$%^&*()_+\-{}:\"<>?,./]+
  • [@A-Za-z0-9~!#$%^&*()_+\-{}:\"<>?,./]+ Matches any of the characters in the character class any times.

regex101 demo

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

Your problems are

  • \b only matches between a "word character" (letter/digit/underscore) and a non-word character (or start/end of string). You therefore need a different method to determine that your match has ended. Since you already have spaces before and after your identifier, you already have such a method and can remove the \bs.
  • - is a metacharacter in a character class and needs to be placed at the start or end of the character class so it isn't interpreted as a range token (as in A-Z).
  • Your identifier starts with a @, but that isn't part of [A-Z], so that can't match. You probably want to (optionally) start the match with @.
  • Apparently the identifier doesn't require a number in position 2 and does allow letters after position 1, so you should combine the three character classes into two (assuming that the first letter needs to be a letter or digit).

That gives you

Created ID @?[A-Z0-9][-A-Z0-9\\/+@#$%^~&*!():]+ has problems

If IDs like -(X@Q) are also valid, you can simplify that to

Created ID [-A-Z0-9\\/+@#$%^~&*!():]+ has problems

Upvotes: 2

Related Questions