Lucky Lucky - 7 months ago 22
Javascript Question

JavaScript RegEx - Minimum characters with Wildcard

I'm working on matching a wildcard search input. it's a name field.
Below are the conditions I need to match.


  1. User must enter at least 3 alphanumeric characters, if he chooses to do a Wildcard search

  2. User may/maynot enter a wildcard at the start or end of the string,but it can be on either side.

  3. Allow spaces between words.



I want to mention that i'm trimming the string before doing a match. This is what I tried so far.

^[^\W_](\s?\w?)*$|^[^\W_]{3,}(\s?\w?)*\*$|^[\*][^\W_]{3,}(\s?\w?)*$


Regular expression visualization

Debuggex Demo

Below are some examples I tried -


  • someone xxx, someone xxx yyy - Passed

  • someone* xxx- Failed

  • someone , someone - Passed



This is the nearest match of what i want- But it fail for these test case.


  • AB asf* -- Fails , this will pass- ABC asf*

  • *AB asf -- Fails , this will pass- *ABC asf



I know I have a condition that says - starts with at least 3 alphanumeric character and repeat space and alphanumeric characters.

That's where I need help with.

Thanks.

ccf ccf
Answer

UPDATE2 This pattern should do:

/^([a-zA-Z0-9]{3,}[^\n*]*\*?|\*[a-zA-Z0-9]{2,}[^\n*]*|[a-zA-Z0-9]{2}\*)$/gm

EXPLANATION:

^                               # assert start of line
 (                              # 1st capturing group starts         
    [a-zA-Z0-9]{3,}             # match 3+ times alphanumeric characters
                  [^\n*]*       # match 0 or more non-newline and non-star (*) characters
                         \*?    # match 0 or one literal star (*) character;
  |                             # OR
    \*                          # match one literal star (*) character
      [a-zA-Z0-9]{2,}           # match 2+ times alphanumeric characters
                     [^\n*]*    # match 0 or more non-newline and non-star (*) characters;
  |                             # OR
    [a-zA-Z0-9]{2}              # match 2 non-newline and non-star (*) characters
                  \*            # match one literal star (*) character
 )                              # 1st capturing group ends       
$                               # assert end of line

REGEX 101 DEMO.