Matt
Matt

Reputation: 71

Combining regular expressions in Python

I'd like to combine the regular expressions \w+ and [a-z] together in Python to only accept a word that is all lowercase, but cannot seem to figure out the right way to do that. Does anyone know how?

Upvotes: -1

Views: 535

Answers (6)

Matt
Matt

Reputation: 71

So I was actually able to get it to work like this : [a-z]\w+.

Upvotes: -1

Aaron Hall
Aaron Hall

Reputation: 394945

Since \w+ is the same as:

[A-Za-z0-9_]+

I think you're looking for this:

[a-z_]+

Or perhaps

[a-z0-9_]+

Upvotes: 0

anon582847382
anon582847382

Reputation: 20351

To find all lowercase words you should use the regular expression as shown in the below example:

re.findall('\b[a-z]+\b', my_string)

You don't need to worry about combining the \w in order to find all lowercase words. The regular expression used will just find strings that only contain lowercase letters.

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

Try the regex as following

\b[a-z]+\b

enter image description here

Live Demo

Upvotes: 2

sabbahillel
sabbahillel

Reputation: 4425

If you already have a word string and want to verify that it is lower case, than you would use the str.islower() function. If you have a string of words separated by spaces, the you can use

  lst = words.split(' ')
  for word in lst:
    print word, 'lower case test is', word.islower()

Note that I did not use list comprehension in order to break up the individual parts.

Upvotes: 0

blueygh2
blueygh2

Reputation: 1538

If you only want lowercase words, all you need is [a-z]+

\w includes uppercase letters, digits, and underscore

Upvotes: 1

Related Questions