IWI
IWI

Reputation: 1608

regex to get first 3 letters and all numbers from a string in javascript

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

Upvotes: 0

Views: 7557

Answers (3)

Nullman
Nullman

Reputation: 4279

how about this one?:

^(\w{3})\D+(\d+)

Upvotes: 1

Sean Kendle
Sean Kendle

Reputation: 3609

Working example on regexr.com: http://regexr.com/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

Upvotes: 3

dawg
dawg

Reputation: 103844

You can do

^(\w{3})\S+\s+(\d{1,2})

Demo

Upvotes: 0

Related Questions