user2217084
user2217084

Reputation: 101

Regex match string that ends with number

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

Upvotes: 10

Views: 60822

Answers (5)

PemaGrg
PemaGrg

Reputation: 730

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

Upvotes: 0

Zacks Delga
Zacks Delga

Reputation: 17

"(c|C).*[0-9]$"

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

Upvotes: 0

Andie2302
Andie2302

Reputation: 4887

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

if (preg_match('/[\s\S]*\d$/', $value)) {
   #match
} else {
  #no match
}

Upvotes: 4

Nyein Mon Soe
Nyein Mon Soe

Reputation: 129

You can use this regular expression pattern

^c[0-9]+$

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382150

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+$

Upvotes: 17

Related Questions