Home > Net >  What is regex for alphanumeric with no spaces?
What is regex for alphanumeric with no spaces?

Time:10-09

I need to match this like:

1. 1234           true
2. 1234 5678      false
3. 1234x          true
4. x1234          true
5. abcd           false
6. abcd 1234      false

so I need to match just a string with numbers only or numbers and characters only and with no spaces (single word). This doesn't really work:

/([0-9])\w /g

CodePudding user response:

Your pattern ([0-9])\w is unanchored, so it can have partial matches.

It also has to start with a digit, and at least 1 word character, have the string to be at least 2 characters long.


You can use anchors, and make sure to match a single digit. For a match only, you can omit the capture group:

^[^\W\d]*\d\w*$
  • ^ Start of string
  • [^\W\d]* Optionally match any word character except a digit
  • \d Match a single digit
  • \w* Match optional word characters
  • $ End of string

Regex demo

Note that \w can also match _

CodePudding user response:

Match the entire string and require a at least one digit:

/^[a-z]*[0-9][a-z0-9]*$/i

See regex proof. Important: i flag (case insensitive).

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [a-z]*                   any character of: 'a' to 'z', 'A' to 'Z' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  [0-9]                    any character of: '0' to '9'
--------------------------------------------------------------------------------
  [a-z0-9]*                any character of: 'a' to 'z', 'A' to 'Z', '0' to '9'
                           (0 or more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  $                        the end of the string

CodePudding user response:

const strings = ['1234','12x3', '12 X'];
console.log(strings.filter(string=> string.match(/^[0-9a-z] $/i)));

CodePudding user response:

regex: /^[0-9a-zA-Z] $/

use test to get boolean result; use match to get matched string

const result = ['1234', '1234 5678', '1234x', 'x1234', 'abcd', 'abcd 1234'].map(str=> /^[0-9a-zA-Z] $/.test(str))
console.log(result)

CodePudding user response:

try this:

/(^[\da-z]*(?!\s)\d [a-z]*$)/g

Regex Tests

  • Related