简体   繁体   中英

Regular expression to extract javascript method calls

I have created string extractor for translations from javascript files. I found jsgettext project which I used as a starting point ( see ).

It uses reqular expression to find calls to __() method inside javascript files. The simple calls are found successfully, but calls with arguments like __('string', { a: 'b'}) are not.

I tried to modify the regular expression to match also method calls with arguments, but without any success (I'm not regular expressions expert).

My question is: How to modify following regular expression to match strings like this?

// this is catched successfully 
// var string = __("Please enter %number% more characters.");

// this is problematic
var string = __("Please enter %number% more characters.", { '%number%' : 2 });

Regular expression:

 $keywords = join('|', array('__'));
 preg_match_all('# (?:' . $keywords . ') \(\\ *" ( (?: (?>[^"\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\" )* ) (?<!\\\\)"\\ *\) #ix', $content, $matches, PREG_SET_ORDER);

Thank you

I don't think you really need to match whole call like:

__("Please enter %number% more characters.", { '%number%' : 2 });

You just need to match:

__("Please enter %number% more characters.",

And leave the rest as it is because those are only arguments that shouldn't be part of translation inside database.

Therefore editing regular expression on lines 81 and 89 to finish with *(?:\\)|,) #ix instead of *\\) #ix should be good enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM