Regex: match a string containing numbers and letters, but not a string of numbers only

Question

I would like to be able to use one regex (if possible) to require the string to match [A-Za-z0-9_], but not allow:

  • Strings containing only numbers and / or characters.
  • Lines beginning or ending with characters
  • Several characters next to each other

Really

  • test_0123
  • t0e1s2t3
  • 0123_test
  • te0_s1t23
  • t_t

Invalid

  • t__t
  • ____
  • 01230123
  • _0123
  • _test
  • _test123
  • test_
  • test123_

Reasons for the rules

The purpose of this is to filter out the usernames for the website I'm working on. I came to the rules for certain reasons.

  • / . /users/#{id} id , . .

  • _test , , , .. _test.example.com

  • t__t . .. t__t.example.com

+3
9

, :

/\A(?!_)(?:[a-z0-9]_?)*[a-z](?:_?[a-z0-9])*(?<!_)\z/i
  • ([a-z] ).
  • ((?!_) (?<!_) ).
  • , , ().

: , , lookahead/lookbehind - , - ?: , -, ?: , -:

/\A(?:[a-z0-9]_?)*[a-z](?:_?[a-z0-9])*\z/i

.

+8

, , , , , . ? , , . ( , , . , .)

, ; , ; ; .. .

+2

:

/^(?=[^_])([A-Za-z0-9]+_?)*[A-Za-z](_?[A-Za-z0-9]+)*$/

.

Edit:

. .

+2

"__", :

([A-Za-z]|[0-9][0-9_]*)([A-Za-z0-9]|_[A-Za-z0-9])*

, :

([A-Za-z]|([0-9]+(_[0-9]+)*([A-Za-z|_[A-Za-z])))([A-Za-z0-9]|_[A-Za-z0-9])*

dang, . Telemachus, , , , . .

+1

, , , , . , , , , . :.

x !~ /[^A-Za-z0-9_]|^_|_$|__|^\d+$/
  • , , _
  • _
  • _s

Rails validates_format_of, , , - , , .

+1
(?=.*[a-zA-Z].*)^[A-Za-z0-9](_?[A-Za-z0-9]+)*$

.

, , , . , , .

0

:

^(([a-zA-Z]([^a-zA-Z0-9]?[a-zA-Z0-9])*)|([0-9]([^a-zA-Z0-9]?[a-zA-Z0-9])*[a-zA-Z]+([^a-zA-Z0-9]?[a-zA-Z0-9])*))$

, , [^ a-zA-Z0-9] [],

0
/^(?![\d_]+$)[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*$/

, , , . lookhhead - (?![\d_]+$) - ( , ), , .

0
[A-Za-z][A-Za-z0-9_]*[A-Za-z]

This will work for your first two rules (since the second rule requires a letter at the beginning and end for the second rule, it automatically requires a letter).

I am not sure that the third rule is possible with regular expressions.

-2
source

Source: https://habr.com/ru/post/1714546/


All Articles