3

I need a javascript regex that accepts any alphanumeric character (can be any amount of characters or 0 characters if an asterisk is present) and a single asterisk anywhere in the string (but it does not need the asterisk).

Matches

*
abc
*abc
abc*
a*bc

Invalid Matches

**
*_abc
*abc*
abc**
**abc

I have

^([A-Za-z\d*]?)+$ 

but that matches multiple asterisks and I'm not sure how to only allow one https://regex101.com/r/a1C9bf/1

adiga
  • 34,372
  • 9
  • 61
  • 83
exk0730
  • 733
  • 5
  • 20

4 Answers4

2

You may use this regex with a negative lookahead:

/^(?!(?:.*\*){2})[A-Za-z\d*]+$/gm

Updated RegEx Demo

Negative lookahead (?!(?:.*\*){2}) fails the match if there are more than one * in input.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 3
    Yup, this is the one, thanks! I'll mark it as the answer in a couple minutes :) – exk0730 Apr 30 '19 at 17:07
  • can you please solve this [issue](https://stackoverflow.com/questions/56023527/mod-rewrite-query-parameter-validation-and-blocking-also-request-url-blocking) – user3637224 May 14 '19 at 11:06
1

Without requiring any look-ahead, you could use ^([\da-zA-Z]+|[\da-zA-Z]*\*[\da-zA-Z]*)$ https://regex101.com/r/xW2IvR/2

junvar
  • 11,151
  • 2
  • 30
  • 46
0

You could do:

^(?=.)[A-Za-z\d]*\*?[A-Za-z\d]*$

This will match any string that that's at least one character long ((?=.)), starts with zero or more alphanumeric characters, contains an optional *, and ends with zero or more alphanumeric characters.

You could also replace [A-Za-z\d] with [^\W_] to make it a little shorter (but slightly harder to read):

^(?=.)[^\W_]*\*?[^\W_]*$
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

You want one match one of two possible cases:

  1. an asterisk surrounded by zero or more alphanumeric characters
  2. one or more alphanumeric characters

Then this is your regex:

^([a-zA-Z\d]*\*[a-zA-Z\d]*|[a-zA-Z\d]+)$
Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47