4

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.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
menteith
  • 596
  • 14
  • 51

3 Answers3

6

Use a positive lookahead assertion:

^(.+)(?=\s)

Capturing group 1 will contain the match.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
James Buck
  • 1,640
  • 9
  • 13
5

^(.+)\s(.+)

with substitution string:

\2, \1

Update:

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

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

medvedev1088
  • 3,645
  • 24
  • 42
-1

I like using named capturing groups:

rawName = RENATA T. GROCHAL
RegexMatch(rawName, "O)^(?P<firstName>.+)\s(?P<lastName>.+)", match)
MsgBox, % match.lastName ", " match.firstName
Forivin
  • 14,780
  • 27
  • 106
  • 199