Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Understanding regular expression in javascript

Hi,
I tried the following regex :
/[^"]*/.exec("rohit");
["rohit"]
/([^"]*)/.exec("rohit");
["rohit", "rohit"]

Open in new window

The second one produces two elements in the array..
I didnt understand the difference between the first and second regex..
As far i understand this should match the first string that does not contain "
But just putting braces the results are different ?

Also
/e/.exec("rohiterohite");
["e"]
/e/g.exec("rohiterohite");
["e"]

Open in new window

putting /g in front should have done a global match and there should be two e in the array
the non global and global seems to be returning the same output.

what does match = /^"([^"]*)"/.exec(program)  do
Looks like it matches a string that starts with " and end with " and in between there are no quotes.
But i tried
 
var string ="rohit bajaj \" rohit \"bajaj";
/^"([^"]*)"/.exec(string);

Open in new window

The above returned null.

Please help me understand the correct meaning of the above regular expressions.
Thanks
SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Dave: the OP is most likely using the Console of a browser. Try it in Chrome.
/e/g.exec("rohiterohite");

If you want to find the second "e", you'll need to call exec again: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Basically the regex engine will stop at first match, but will keep the LastIndex value, that will be used on the next run.
var string ="rohit bajaj \" rohit \"bajaj";
/^"([^"]*)"/.exec(string);

The null value is what it should return.
The first and last " in var string ="rohit bajaj \" rohit \"bajaj"; are string delimiters. They are not part of the string.

Use this instead:
var string ="\"rohit bajaj \" rohit \"bajaj\"";
/^"([^"]*)"/.exec(string);
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks kaufmed. Yes, it's "The full string of characters matched".