Regex match string that ends with number
Asked Answered
F

5

9

What is a regex to match a string that ends with a number for example

"c1234" - match
"c12" - match
"c" - no match

Tried this but it doesn't work

(?|c(?|[0-9]*$))

Thanks again,

The beggining string needs to be specific too

Festination answered 20/5, 2015 at 8:39 Comment(2)
What language are you using?Romney
I'm using PHP preg_matchFestination
B
17

Just use

\d$

to check your string ends with a digit

If you want your string to be a "c" followed by some digits, use

c\d+$
Bitterroot answered 20/5, 2015 at 8:40 Comment(5)
@u what ? How are you testing that ?Yvoneyvonne
@user2217084: It works for any string that ends with a digit. Have you tried it?Animadvert
Regular expression c\d$Festination
The beggining string needs to be specific tooFestination
@Festination Note the + behind the d.Leshalesher
C
5

You can use this regular expression pattern

^c[0-9]+$
Covetous answered 20/5, 2015 at 8:58 Comment(2)
It's about PHP not Java.Leshalesher
Sorry,I forgot to read comment at first and I just read the question.I just want to find the correct pattern for the questioner.Sorry about that.Covetous
S
4

To match any string ending with a digit use: [\s\S]*\d$

if (preg_match('/[\s\S]*\d$/', $value)) {
   #match
} else {
  #no match
}
Squalene answered 20/5, 2015 at 9:20 Comment(0)
O
0
"(c|C).*[0-9]$"

See working example: https://regex101.com/r/4Q2chL/3

Ornis answered 8/10, 2018 at 21:39 Comment(1)
This is matching c;,:.?!$+0Animadvert
H
0

dynamic way would be:

import re
word_list = ["c1234", "c12" ,"c"]
for word in word_list:
    m = re.search(r'.*\d+',word)
    if m is not None:
        print(m.group(),"-match")
    else:
        print(word[-1], "- nomatch")

RESULT:

c1234 -match
c12 -match
c - nomatch
Hosea answered 1/10, 2019 at 5:1 Comment(3)
It is a PHP question, not Python.Animadvert
ops, since it wasn't mentioned in the question, gave my own suggestion :)Hosea
It was mentionned, look at the tags.Animadvert

© 2022 - 2024 — McMap. All rights reserved.