2

Here are two lines from some text that I wanted to change

Dorset Rd (5) - 2018-12-14 11-01-05
Crampton Chas - Sandarra Blvd - 2018-12-27 12-31-56

I’m trying to move the date and time from the end of each line to the start to produce this

2018-12-14 11-01-05 - Dorset Rd (5)
2018-12-27 12-31-56 - Crampton Chas - Sandarra Blvd

Through reading this forum (thanks to you all), I have come up with the following regex

(^.*)\s-\s(.*$)

And used this as the replacement

$2 - $1

This works fine, but I have two questions:

  1. I’m wondering why the ‘\s-\s’ found the last occurrence of ‘ - ‘ instead of the first?
  2. Could this have been better done by picking up the last 19 characters and somehow moving them to the start?
Red Ochre
  • 23
  • 2

1 Answers1

1

I’m wondering why the ‘\s-\s’ found the last occurrence of ‘ - ‘ instead of the first?

Because the first * is greedy. It matches everything first, then it backtracks until the stuff after it matches the rest of the string. See this question.

Could this have been better done by picking up the last 19 characters and somehow moving them to the start?

If your date format will always have 19 characters, sure!

^(.*) - (.{19})$

replace with the same replacement.

Not sure if this is "better" though, without knowing what you mean by "better".

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I've now learnt what 'greedy' means. Thx I noticed that where I used `(^.*)` you used `^(.*)`. Is there a difference? – Red Ochre Jan 01 '19 at 00:21
  • @RedOchre there is no difference. `^` matches a zero width string, so it doesn’t matter if it is in the group or not. – Sweeper Jan 01 '19 at 00:34