-1

I want to test if a sentence like type var1,var2,var3 is matching a text declaration or not.

So, I used the following code :

var text = "int a1,a2,a3",
     reg = /int ((([a-z_A-Z]+[0-9]*),)+)$/g;

if (reg.test(text)) console.log(true);
else console.log(false)
The problem is that this regular expression returns false on text that is supposed to be true.

Could someone help me find a good regular expression matching expressions as in the example above?

h3t1
  • 1,126
  • 2
  • 18
  • 29

2 Answers2

2

You have a couple of mistekes.

  1. As you wrote, the last coma is required at the end of the line.
  2. I suppose you also want to match int abc123 as correct string, so you need to include letter to other characters
  3. Avoid using capturing groups for just testing strings.

const str = 'int a1,a2,a3';
const regex = /int (?:[a-zA-Z_](?:[a-zA-Z0-9_])*(?:\,|$))+/g

console.log(regex.test(str));
1

You will need to add ? after the comma ,.

This token ? matches between zero and one.

Notice that the last number in your text a3 does not have , afterward.

int ((([a-z_A-Z]+[0-9]*),?)+)$
Ibrahim
  • 6,006
  • 3
  • 39
  • 50