RegEx: Match everything up to the last space without including it

。_饼干妹妹 提交于 2019-12-13 13:26:57

问题


I'd like to match everything in a string up to the last space but without including it. For the sake of example, I would like to match characters I put in bold:

RENATA T. GROCHAL

So far I have ^(.+\s)(.+) However, it matches the last space and I don't want it to. RegEx should work also for other languages than English, as mine does.

EDIT: I didn't mention that the second capturing group should not contain a space – it should be GROCHAL not GROCHAL with a space before it.

EDIT 2: My new RegEx based on what the two answers have provided is: ^((.+)(?=\s))\s(.+) and the RegEx used to replace the matches is \3, \1. It does the expected result:

GROCHAL, RENATa T.

Any improvements would be desirable.


回答1:


^(.+)\s(.+)

with substitution string:

\2, \1

Update:

Another version that can collapse extra spaces between the 2 capturing groups:

^(.+?)\s+(\S+)$




回答2:


Use a positive lookahead assertion:

^(.+)(?=\s)

Capturing group 1 will contain the match.




回答3:


I like using named capturing groups:

rawName = RENATA T. GROCHAL
RegexMatch(rawName, "O)^(?P<firstName>.+)\s(?P<lastName>.+)", match)
MsgBox, % match.lastName ", " match.firstName


来源:https://stackoverflow.com/questions/36247497/regex-match-everything-up-to-the-last-space-without-including-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!