samach
samach

Reputation: 3394

Regex for detecting preceeding and proceeding lowercase letters and numbers

I am trying to find a particular pattern in my strings and my knowledge of regex is quite basic. To find lower case letters I can use [a-z0-9]+ but how would I go about finding the preceding and proceding characters?

Allowed examples: (A), AB, ABC, [ABC], .AB' , @ABCD#. In essence only uppercase characters(any length), or uppercase(any length) with preceding or proceding or both(front and back), special chars.
Not Allowed: abABCaa , ABCaa , aaAB , 123ABC , 12ABGGabc , aaBaa etc. In essence uppercase letters(any length) with preceding or proceding or both, alphabets or numbers.

How can I write a regex that filters either the allowed examples or the not allowed examples? Hope I am clear

Upvotes: 2

Views: 505

Answers (4)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

It's much easier. Simply check for a match against:

"^\\p{P}*[A-Z]+\\p{P}*$"

\p{P} matches any punctuation character.

^ and $ can be dropped if you're using the .matches() method.

So this matches AAB, #A, A. and fails 1A, aAa, aA and Aa.

Upvotes: 1

Sednus
Sednus

Reputation: 2113

This will match 3 groups: the Matched uppercase, the characters preceding it and the characters after it. If groups are not desired, just remove the parenthesis.

([^a-z0-9]*)([A-Z]+)([^a-z0-9]*)

For more information about matching and grouping please refer to the proper Javadoc . Also, a suggestion for testing regex online

Upvotes: 4

Toto
Toto

Reputation: 91488

How about simple:

\b[A-Z]+\b

That will match uppercase letters surrounded by other characters than word character

Upvotes: 1

MirrorMirror
MirrorMirror

Reputation: 188

not sure this can be done with regex. try it algorithmically by comparing :

  • start loop all characters of the string (alpha chars):

    CurCharIsUpper = (curchar.uppercase == curchar.lower) ? false: true; if (PrevCharIsUpper == CurCharIsUpper) blahblah; PrevCharIsUpper = CurCharIsUpper;

  • end loop

Upvotes: -1

Related Questions