Regex Help, Search for function names and return them
Need a regex here that will take a file line by line and output all of the function names. So for example:
function apples_and_bananas ($params, $arguments) {
print "hello world of yellow and red";
}
And return apples_and_bananas
Using regex so that it runs fast when doing line by line string manipula开发者_JAVA技巧tion. Unless there is a better way of doing this. I don't know how to generate regex it is so complicated and I was never taught it, can you also point to a good document to learn? This is for c# in a windows form app.
According to the page "Constants" @ php.net, the regex should be:
function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(
This regex supposed to be correct for almost every language.
Assuming you're using PHP, and want to use PHP for the code to find function names you can use this code. If you're using a different language the code should be fairly similar. Just need to read the file in, and match it against the regex expression /function\s+(\w*)\s*\(/
:
$filename = 'yourfile.php';
$matches = array();
preg_match_all('/function\s+(\w*)\s*\(/', file_get_contents($filename), $matches);
$matches = $matches[1];
// Matches contains array of function names
I've tested this for you.
The captured string form the regex below should be the function name.
/^function\s+([^\s]+)\s/
You should be able to google for regex tutorials to learn how they work. You can also check out Mastering Regular Expressions.
This will most likely do everything you need:
/function\s+([^\s\(]+)/
However, if you want to restrict the names of functions to only those acceptable in PHP, you need the longer regex @Dor suggested.
精彩评论