1

I am trying to validate a string of the pattern IN-XXXXXXXX-X, where X is an alphumeric value. For It I need to write the regex expression

The regex I write is

/^IN-\w{8}-\w/g 

But it validates alphanumeric as well as underscores in place of X.The other way would be

 /^IN-[A-Za-z0-9]{8}-[A-Za-z0-9]/g 

However this seems way to long. Is there a shorthand to write [A-Za-z0-9] in order to validate alphanumeric values.

5
  • Which flavour are you using?
    – Sweeper
    Commented Nov 13, 2017 at 17:47
  • AFAIK there isn't... unless you're using a specific flavor of regex, such as sed, and then you can use [:alnum:] for example
    – Nir Alfasi
    Commented Nov 13, 2017 at 17:47
  • 1
    Why do you want a shorter way of doing it in the first place?
    – Sweeper
    Commented Nov 13, 2017 at 17:49
  • @Sweeper My patten can include IN-X-XX-X-XXXX-XX and so on, so writing the same thing muliple times can make the regex look really longer and hence that made me think if there is a shorthand to write it Commented Nov 13, 2017 at 17:51
  • 1
    You could do ^IN-[[:alnum:]]{8}-[[:alnum:]] or ^IN-(?i)[a-z0-9]{8}-[a-z0-9]
    – ctwheels
    Commented Nov 13, 2017 at 18:44

1 Answer 1

7

How about using [^\W_] to match alphanumeric characters?

\W - non-word characters. Basically, we match anything except non-word characters and underscores, which is the set of alphanumeric characters.

The regex would shorten to

^IN-[^\W_]{8}-[^\W_]

Try it here: https://regex101.com/r/l3rqsq/1

1
  • Yes that does work and it was what I was looking for. Commented Nov 13, 2017 at 17:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.