RegEx: Match everything up to the last space witho

2019-06-24 07:04发布

问题:

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