Reputation: 721
I have a regex that can split a string at the first digit
var name = 'Achill Road Boy 1:30 Ayr'
var horsedata = name.match(/^(\D+)(.*)$/);
var horse = horsedata[1]; // "Achill Road Boy "
var meeting = horsedata[2]; // "1:30 Ayr"
However, I now need to further split
var meetingdata = meeting.match(?what is the regex);
var racetime = meetingdata[1]; // "1:30 "
var course = meetingdata[2]; // "Ayr"
What is the regex to split the string at the first letter?
Upvotes: 0
Views: 2250
Reputation: 29463
Given the string:
1:30 Ayr
The capture group from this regex will give you Ayr
:
^[^a-zA-Z]*([a-zA-Z\s]+)$
Regular Expression Key:
^
- start of match[^a-zA-Z]*
- from 0 to any number of non-alphabet characters([a-zA-Z\s]+)
- capture group: from 1 to any number of alphabet characters and spaces$
- end of matchUpvotes: 0
Reputation: 303
You can use single regex to do that:
^([^\d]+) +(\d+):(\d+) (.*)$
It will catch name, hour and minute separately, and track name, in groups 1, 2, 3 and 4.
Note that I have added ^ and $ to the expression, meaning that this expression should match given string completely, from start to finish, which I think are useful safeguards against matching something inside the string which you didn't expect initially. They may, however, interfere with your task, so you can remove them if you don't need them.
When tinkering with regular expressions I always use this nifty tool, http://regex101.com - it has a very useful interface to debug regular expressions and also their execution time. Here's a link to a regular expression above: https://regex101.com/r/jYgc9K/1. It also gives you a nice clear breakdown of this regular expression:
Full match 0-24 `Achill Road Boy 1:30 Ayr`
Group 1. 0-15 `Achill Road Boy`
Group 2. 16-17 `1`
Group 3. 18-20 `30`
Group 4. 21-24 `Ayr`
Last, word of advice: there's a famous saying by Jamie Zawinski, a very smart guy. It goes like this:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems".
There's a lot of truth in this saying.
Upvotes: 5