javascriptregexregex-group

How to write a regex expression to check a valid XML element NCName in javascript?


NCName means that it must start with a letter or underscore, and can only contain letters, digits, underscores, hyphens, and periods.I have try to write the regex like this,but I think it may be wrong.

if(/^([_]|[a-zA-Z]+[\w\W])$/.test('abc' ))  console.log('match')

Solution

  • Your ^([_]|[a-zA-Z]+[\w\W])$ pattern matches a string that is either equal to _ ([_]) or (|) is formed of 1+ letters ([a-zA-Z]+) followed with any char ([\w\W]). So, it cannot validate the strings of the type you mention.

    You may use

    /^[a-zA-Z_][\w.-]*$/
    

    See the regex demo and the graph (source) below:

    enter image description here

    Details