user2411447
user2411447

Reputation:

preg_match php to match javascript

i have this function in php :

$html_price = "text text 12 eur or $ 22,01 text text";
preg_match_all('/(?<=|^)(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?)(?:\ |)(?:\$|usd|eur)+(?=|$)|(?:\$|usd|eur)(?:| )(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?)/', strtolower($html_price), $price_array1);
print_r($price_array1);

Now i want use in javascript the same regex but i have an error: SyntaxError: invalid quantifier

my javascript :

maxime_string = "((?<=|^)(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?)(?:\ |)(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)+(?=|$)|(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)(?:| )(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?))";
maxime_regex = new RegExp(maxime_string);
var text = "text text 12 eur or $ 22,01 text text";          
var result = text.match(maxime_regex);
var max = result.length;
alert(result.length);
for (i = 0; i < max; i++) 
{ 
document.write(result[i] + "<br/>");
} 

Can you help me ?

Upvotes: 0

Views: 557

Answers (1)

Bergi
Bergi

Reputation: 665574

JavaScript does not support lookbehind - that's probably where you got your error from. Some things:

  • (?<=|^) makes no sense. It's a lookbehind demanding either nothing or string begin to come before this - it's always true. And if you want to match the string start, use a single ^.
  • (?:.[0-9]*)? - I guess you wanted to escape the dot so it matches literally
  • (?:\ |): You do not need to escape blanks. And instead of an alternative "nothing", you should just make the blank optional: " ?".
  • (?=|$) makes as much sense as the first group.
  • € is a broken unicode character?

Also, you should consider using a regex literal instead of the RegExp constructor with a string literal - it eats one level of backslash escaping. And it seems you're missing the global flag, so that you get back all matches. Try this:

var maxime_regex = /((?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:\.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?) ?(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)+|(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€) ?(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:\.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] ​*)?))/g

This post does not include any effort to understand, optimize or shorten that regex monster

Upvotes: 6

Related Questions