Home > Blockchain >  How to detect only combination of numbers and letters by regex
How to detect only combination of numbers and letters by regex

Time:05-17

I need to detect only the word from a sentence where only combination of the numbers and letters exists by regex.

I am using this https://regex101.com/r/eSlu2I/1 ^[a-zA-Z0-9]* regex.

Here last two ones should be excluded. Can anyone help me with this?

CodePudding user response:

Use

^(?![a-zA-Z] \b)[a-zA-Z0-9]*

See regex proof.

EXPLANATION

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [a-zA-Z]                 any character of: 'a' to 'z', 'A' to 'Z'
                             (1 or more times (matching the most
                             amount possible))
--------------------------------------------------------------------------------
    \b                       the boundary between a word char (\w)
                             and something that is not a word char
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [a-zA-Z0-9]*             any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9' (0 or more times (matching the
                           most amount possible)) 

CodePudding user response:

You can use the following regex:

\w*\d\w*

Explanation:

  • \w*: optional combination of alphanumeric characters
  • \d: digit
  • \w*: optional combination of alphanumeric characters

Try it here.


EDIT: In case you require the presence of at least one letter together with the number, you can instead use the following regex:

\w*(\d[A-Za-z]|[A-Za-z]\d)\w*

Explanation:

  • \w*: optional combination of alphanumeric characters
  • (\d[A-Za-z]|[A-Za-z]\d):
    • \d[A-Za-z]|: digit alphabetical character or
    • [A-Za-z]\d: alphabetical character digit
  • \w*: optional combination of alphanumeric characters
  • Related