Qualification check for regex - allow spaces in the middle, but not start and end

I am allowing space for this regex as follows:

JavaScript:

var re_username = /^[a-zA-Z\040\.\-]+$/;
var is_username = re_username.test($('#chatusername').val());
console.log(is_username);   

      

... but I want to ban it at the beginning and at the end. This worked:

JavaScript:

var re_username = /^[a-zA-Z]+[a-zA-Z\040\.\-]+[a-zA-Z\.]+$/;

      

... but I need to enter at least 3 (<3 digits returns false, although I enter, for example A) digits for the regex to return true, which causes problems with adding classes and others ...

I found this for this, allowing spaces at the beginning and end

JavaScript:

var re_username = /^\S+(?: \S+)*$/

      

But this allows all characters .... How can I match my target regex? I tried this ... but it didn't work anymore.

var re_username = /^\S+([a-zA-Z]\040\S+)*$/; 

      

+3


source to share


1 answer


Using

var re_username = /^[a-zA-Z.-]+(?:\040+[a-zA-Z.-]+)*$/;

      

It will match

  • ^

    - beginning of line
  • [a-zA-Z.-]+

    - 1 + letters, .

    and-

  • (?:\040+[a-zA-Z.-]+)*

    - 0+ sequences
    • \040+

      - 1 + regular spaces
    • [a-zA-Z.-]+

      - 1 + letters, .

      and-

  • $

    - end of line

See regex demo .



NOTE. If you don't want to allow sequential multiple spaces, remove +

after \040

.

Another less efficient way is through lookaheads:

var re_username = /^(?!\040|.*\040$)[a-zA-Z\040.-]+$/;
                    ^^^^^^^^^^^^^^^ 

      

Here, a negative lookahead (?!\040|.*\040$)

will fail if a space is found at the beginning of the line or after any 0+ ( .*

) characters at the end of the line ( $

).

+1


source







All Articles