Search code examples
regexvalidationxregexp

XRegExp regular expression to allow single space between characters


I am working with XRegExp Regex. I would like to have a space between my character also I need to have special characters enables. I have managed to add special characters allowed but I am not able to have a space allowed.

My regex unicodeWord = XRegExp("^(\\p{L}|[0-9][\s])+$");

It allows character like

Wèlcome

but not

Hi Wèlcome

//Alphanumeric validation
function isAlphanumeric(str) { 
    var unicodeWord = XRegExp("^[\p{L}\d]+(?:\s+[\p{L}\d]+)*$"); 
    result = unicodeWord.test(str);
    return result;
}


été altérée sûr générateurs

But this dosnt match this Alphanumeric.


Solution

  • You need to change your regex like,

    unicodeWord = XRegExp("^[\\p{L}\\d]+(?:\\s[\\p{L}\\d]+)*$");
    
    • [\\p{L}\\d]+ Matches one or more letters or digits.
    • (?:\\s[\\p{L}\\d]+)* followed by zero or more (space followed by one or more letters or digits)

    OR

    unicodeWord = XRegExp("^[\\p{L}\\d]+(?:\\s[\\p{L}\\d]+)?$");
    

    ? in (?:\\s[\\p{L}\\d]+)? would turn the previous token (?:\\s[\\p{L}\\d]+) as optional.