Reputation: 629
I have this Python regex: [A-Za-z0-9_\s]+
How can I set it up so that it allows spaces, but doesn't allow spaces as the last character.
Given the string
"Monthly Report Aug 27th 2013 - New York"
I'd like it to match
"Monthly Report Aug 27th 2013"
not
"Monthly Report Aug 27th 2013 "
Upvotes: 2
Views: 1798
Reputation: 31025
You can use this regex
([\w\s]+)\s
MATCH 1
1. [0-28] `Monthly Report Aug 27th 2013`
Upvotes: 0
Reputation: 611
Python supports the "non-whitespace" wildcard: \S
(capitalized wild cards tend to be the opposite of lowercase.) So you could use something like this:
r'[A-Za-z0-9_\s]+\S$'
Upvotes: 1
Reputation: 89565
I will write it like this:
[A-Za-z0-9_]+(?:\s+[A-Za-z0-9_]+)*
Note: if you don't use the re.LOCALE
or re.UNICODE
options, the pattern can be shorten to:
\w+(?:\s+\w+)*
Upvotes: 4
Reputation: 2269
Try something like [A-Za-z0-9_\s]+[A-Za-z0-9_]. You just add an extra character on the end of the regular expression that doesn't match a space.
Upvotes: 0