Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a Function Call?

Tags:

regex

php

I'm looking to simply pull some quoted text out of a function call and was wondering if I could get some help with regex?

The string would look something like this: 'MyFunction("MyStringArg");'

I would, essentially, like to scan a file for any lines that call 'MyFunction', and then capture the string literal within the quotes.

Follow-up Question
How would I go about avoiding commented lines with this?

Update
I was able to solve my problem with:
MyFunction\s*\(\s*"(.*?)\"\s*\)\s*;

Thanks @devyndraen and everyone for your help!

like image 344
Selosindis Avatar asked Jun 13 '26 00:06

Selosindis


2 Answers

I'm not sure what kinds of requirements for formatting you have, so I included the assumption that there could be any amount of space in the normal programming places there could be some.

The resultant string will be in the \1 backreference.

MyFunction\s*\(\s*"(.*?)\"\s*\)\s*;

http://rubular.com/r/qVsaqJS6gJ

like image 57
devyndraen Avatar answered Jun 15 '26 13:06

devyndraen


I would suggest this non-greedy regex with flag s (DOTALL in Java) (assuming there are no comments inside the parenthesis of this function call:

$regex = '/MyFunction.*?\(.*?"(.*?)".*?\).*?;/s';

If you use preg_match($regex, $str, $matches) then argument will be available in $matches[1].

like image 33
anubhava Avatar answered Jun 15 '26 12:06

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!