简体   繁体   中英

Don't allow space as a last character

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 "

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+)*

Python支持“非空白”通配符: \\S (大写的通配符通常与小写字母相反。)因此,您可以使用如下代码:

r'[A-Za-z0-9_\s]+\S$'

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.

You can use this regex

([\w\s]+)\s

Working demo

MATCH 1
1.  [0-28]  `Monthly Report Aug 27th 2013`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM