Regular expression to allow alphanumeric, max one space etc

后端 未结 2 1570
不思量自难忘°
不思量自难忘° 2021-01-24 22:49

I\'m opening this thread that is really similar to another one but I cannot figure out an issue : I have an input field that allow a alphanumeric string with an optional unique

相关标签:
2条回答
  • 2021-01-24 23:14

    This is a simpler regex using \w (word class):

    ^([\w]+(\s*))$
    

    Test

    It's instantaneous in JavaSript

    var input = "dzdff5464zdiophjazdioj ttttttttt zoddzdffdziophjazdioj ttttttttt  zoddzdffdzdff ttttt zoddzdfff ttttt zoddzdfff ttttt zoddzdfff ttttt  zoddzdfff ttttt zoddzdfff ttttt zoddzdfff ttttt zoddzdfff ttttt  zoddzdfff ttttt zo999  ddzdfff ttttt zoddzdfff ttttt zoddzdff";
    
    var re = /([\w]+(\s*))/g;
    
    console.log(input.replace(re, "boo"));
    
    0 讨论(0)
  • 2021-01-24 23:23

    I suggest changing the expression to something like this:

    (?i)^[0-9a-z]+(?:\s[0-9a-z]+)*$

    enter image description here

    This is functionally similar in that it'll match all alphanumeric characters which are delimited by a single space. A major difference is that I moved the initial word check to the front of the expression, then made a non capture group (?:...) for the remaining space delimited words.

    Non capture groups (?:...) are faster then capture groups (...) because the regex engine doesn't need to retain matched values. And by moving the space \s to the front of the word group on repeat words the engine doesn't need to validate the first character in the group is included in the character class.

    You also have a typo in your character class [0-9a-zA-z] the last z should probably be upper case. This A-z format will likely have some odd unexpected results. In my expression I simply added a (?i) to the beginning to force the regex engine to shift into case insensitive mode, and I dropped the character class to [0-9a-z].

    In my testing I see that your expression ^([0-9a-z]+ ?)*$ takes about 0.03 seconds to process your sample text with 2 extra spaces toward the end. My recommended expression completes the same test in about 0.000022 seconds. WOW that's an amazing delta.

    0 讨论(0)
提交回复
热议问题