user2096512
user2096512

Reputation: 469

Regex to test that a string contains both upper case and lower case letters

I'm looking for a Regex to test that a string contains both upper case and lower case letters. I found a few threads on this but and they suggest using a forward lookup, but I can't seem to make it fit in with the rest of my expression, I'm looking to test for this:

<b>James Smith (ecg)</b>

But exclude this (the (ecg) is always lower case):

<b>JAMES SMITH (ecg)</b>

So far I have this:

<b>[A-z\s\W]+(\(ecg\))?\W?<\/b>

Which works but will also match if it's all in caps or all in lower case. I tried this but it's still matching everything:

<b>(.*(?=.*[a-z])(?=.*[A-Z]).*)[A-z\s\W]+(\(ecg\))?\W?<\/b>

Upvotes: 4

Views: 3391

Answers (2)

Brendan Abel
Brendan Abel

Reputation: 37499

You could use an OR condition, checking for a lowercase letter followed by any number of other characters and an uppercase letter, OR, an uppercase letter followed by any number of other characters and at least one lowercase letter.

(([a-z].*[A-Z])|([A-Z].*[a-z])) \(ecg\)

Example

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

You can use

<b>(?=[A-Z\s]*[a-z])(?=[a-z\s]*[A-Z])[\sA-Za-z]*(?:\(ecg\))?<\/b>

See the regex demo

Details

  • <b> - a <b> text
  • (?=[A-Z\s]*[a-z]) - after 0 or more uppercase letters or whitespaces, there must be at least one lowercase letter
  • (?=[a-z\s]*[A-Z]) - after 0 or more lowercase letters or whitespaces, there must be at least one uppercase letter
  • [\sA-Za-z]* - zero or more letters/whitespaces
  • (?:\(ecg\))? - an optional (ecg) text
  • <\/b> - a </b> text.

Upvotes: 2

Related Questions