Kiksy
Kiksy

Reputation: 1292

Regex - match a certain number of numeric when followed by letter

I want to match a string where it is 1-4 numbers, followed by a specific letter.

For example, if my string was

'The hardness for this rubber is 90a , the hardness for the other was 120a'

I want to grab the values '90a' and '120a'.

I tried ^[0-9]{0,4}[a]$ and ^([0-9]{0,4})[g]$

Bonus points if it can match it with a space after the numbers. eg/

'Rubber number 1 was 98 a , rubber number 2 was 89 a'

would match

'98 a'

and

'89 a'

Upvotes: 0

Views: 64

Answers (2)

aelor
aelor

Reputation: 11116

this will match

(\d{1,4} \s*\w)

\d+ for one or more numbers
\s* for zero or more spaces
\w for a character

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

No problem:

\b\d{1,4} *a\b

Explanation:

\b        # Start of number (or use (?<!\d) if you're not on JavaScript)
\d{1,4}   # Match 1-4 digits
[ ]*      # Match optional space(s) 
a         # Match the letter "a" 
\b        # Make sure no letter/digit follows

Upvotes: 2

Related Questions