简体   繁体   中英

What is regex for alphanumeric with no spaces?

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

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 _

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

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

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)

try this:

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

Regex Tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM