Regex: Check if string contains at least one digit

后端 未结 9 2126
盖世英雄少女心
盖世英雄少女心 2020-12-09 07:40

I have got a text string like this:

test1test

I want to check if it contains at least one digit using a regex.

What would this reg

9条回答
  •  感动是毒
    2020-12-09 07:59

    Another possible solution, in case you're looking for all the words in a given string, which contain a number

    Pattern

    \w*\d{1,}\w*
    
    • \w* - Matches 0 or more instances of [A-Za-z0-9_]
    • \d{1,} - Matches 1 or more instances of a number
    • \w* - Matches 0 or more instances of [A-Za-z0-9_]

    The whole point in \w* is to allow not having a character in the beginning or at the end of a word. This enables capturing the first and last words in the text.

    If the goal here is to only get the numbers without the words, you can omit both \w*.

    Given the string

    Hello world 1 4m very happy to be here, my name is W1lly W0nk4
    

    Matches

    1 4m W1lly W0nk4
    

    Check this example in regexr - https://regexr.com/5ff7q

提交回复
热议问题