skip to Main Content

hi i need to check the validity of all groups and the mixed possibility of creating a world.

for example:

asd
a s d
4 s   d
444ssddd
aaaaa444ssss dddd

must all match.
while:

aesd
zxaxvd

anything that have not that pattern

i’ve try with something like this:

(a*|4*|4* *|a* *)(s*|s* *)(d*|d* *)

but this always return true, while should match the entire pattern group:

const regex = '(a*|4*|4* *|a* *)(s*|s* *)(d*|d* *)';
const re = new RegExp(regex, "gi");
const deleteMessage = re.test(text);

3

Answers


  1. The following should work:

    const words=`asd
    a s d
     a a 4  as      dd    d  
    4 s   d
    444ssddd
    aaaaa444ssss dddd
    aesd
    zxaxvd
    aa a s4s    d d`.split("n");
    
    words.forEach(w=>console.log(w,w.match(/^ *[a4][a4 ]*s[s ]*d[d ]*$/)));

    In your regexp you used the * quantifier which also allows zero occurrences, while in my pattern I require at least one occurrence of the letters a or 4, s and d.

    Login or Signup to reply.
  2. Your pattern has no bounds and doesn’t actually require anything because it uses asterisks for everything, so even an empty string is valid. This should do the trick by adding start and end bounds as well as requiring at least one character from each grouping.

    ^([a4]+ *)(s+ *)(d+ *)$
    
    Login or Signup to reply.
  3. There are two issues with your regex:

    1. everything is optional, so it will match an empty string;
    2. because you don’t have any anchors on your regex, it will thus match every input (since all strings have empty strings in them).

    You can fix that by using this regex:

    ^(?:a*4+|a+4*) *s+ *d+ *$
    

    which matches:

    • ^ : beginning of string
    • (?:a*4+|a+4*) : 0 or more a followed by 1 or more 4; or 1 or more a followed by 0 or more 4
    • * : some number of spaces
    • s+ : 1 or more s
    • * : some number of spaces
    • d+ : 1 or more d
    • * : some number of spaces
    • $ : end of string

    Regex demo on regex101

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search