Reputation: 927
So i have to find all calls of functions in code like: _t(anything) Also there can be parameters given to those calls like: "_t(anything, _t(anything2))" and for such examples i want to match only top call of _t() is there any way to do this ?
Upvotes: 0
Views: 92
Reputation: 567
Programming is about picking the right tool for the job, and regular expressions is not really the right tool for matching only the top-level portion of a function. However, it is a rather simple task to write a program to grab the top level portion, here's a program, written in C++, that will accomplish this. It will parse the string stored in the variable "str", and find the top level portions of the function stored in "func", so in this case it finds "_t("
#include <iostream>
#include <string>
using namespace std;
int main () {
string str = "_t(another, anything)\nanything0 _t(anything, _t(anything2))\n_t(anything)\n_m(this, should, not, match)\n_t(anything1, anything2)";
string func = "_t(";
int pos = 0;
int lastPos = 0;
while (pos != -1) {
pos = str.find (func, lastPos);
if (pos == -1) break;
int depth = 1;
string tmp;
pos += func.size ();
while (depth > 0) {
if (str[pos] == '(') {
depth++;
}
else if (str[pos] == ')') {
depth--;
}
if (depth != 0) {
tmp += str[pos];
}
pos++;
}
cout << tmp << endl;
lastPos = pos;
}
return 0;
}
Given the following input (stored in the string "str"):
_t(another, anything)
anything0 _t(anything, _t(anything2))
_t(anything)
_m(this, should, not, match)
_t(anything1, anything2)
The following is the output:
another, anything
anything, _t(anything2)
anything
anything1, anything2
_t\(([\w\d _\(\),]+)?\)
Here's an example, in PHP (as you said you were using in another comment):
<?php
$pattern = '/_t\(([\w\d _\(\),]+)?\)/';
$subject = '_t(another, anything)\nanything0 _t(anything, _t(anything2))\n_t(anything)\n_m(this, should, not, match)\n_t(anything1, anything2)';
preg_match_all ($pattern, $subject, $matches);
print_r ($matches);
?>
The output from this is as follows:
Array
(
[0] => Array
(
[0] => _t(another, anything)
[1] => _t(anything, _t(anything2))
[2] => _t(anything)
[3] => _t(anything1, anything2)
)
[1] => Array
(
[0] => another, anything
[1] => anything, _t(anything2)
[2] => anything
[3] => anything1, anything2
)
)
And that seems to match what you're looking for, in the $matches[1] array.
Upvotes: 1
Reputation: 20424
I'm not sure if you want to match the function names only or remove parameters (including non-top-level calls). Anyways here is a replace regex which outputs:
_t()
_t()
_t()
with
_t(anything, _t(anything2))
_t(anything)
_t(anything1, anything2)
as input:
/(_t\().*(\))/\1\2/g
Upvotes: 0