I am trying my hand at regex for the first time. The input is a day of the week and a number, like SUNDAY 2
or WEDNESDAY 25
. I need a regex to make the output SUN 2
or WED 25
, i tried ^.{0,3}\d+
but it does not seem to work. Would someone mind helping me out?
Things to notice: The date can have either 1 or 2 digits
I am trying my hand at regex for the first time. The input is a day of the week and a number, like SUNDAY 2
or WEDNESDAY 25
. I need a regex to make the output SUN 2
or WED 25
, i tried ^.{0,3}\d+
but it does not seem to work. Would someone mind helping me out?
Things to notice: The date can have either 1 or 2 digits
Share Improve this question edited Feb 23, 2017 at 22:14 IWI asked Feb 23, 2017 at 21:56 IWIIWI 1,6046 gold badges31 silver badges61 bronze badges 2- What is the programming language? – Wiktor Stribiżew Commented Feb 23, 2017 at 21:58
-
Search for:
\b([a-zA-Z]{3})[a-zA-Z]+(\s+\d{1,2})
and replace by `"$1$2" – anubhava Commented Feb 23, 2017 at 22:00
3 Answers
Reset to default 3Working example on regexr.: http://regexr./3fcg7
First of all, you're missing the space \s
:
^.{0,3}\s?\d+
But, that's still not enough, you need to acknowledge and ignore all the following letters, and then grab only the numbers. You can do this with regex groups. (They're zero based, with Zero being the entire match, then 1,2, etc would be the groups you create):
(^[A-Z]{3})[A-Z]*\s?(\d)+
That's (First group) any capital letter (at the beginning of the string) 3 times, then any capital letter 0 or more times, then a space, then (second group) any digit 1 or more times.
So for SUNDAY 2
Group 0: Entire match
Group 1: SUN
Group 2: 2
how about this one?:
^(\w{3})\D+(\d+)
You can do
^(\w{3})\S+\s+(\d{1,2})
Demo
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131250a4612982.html
评论列表(0条)