Skip to content
Snippets Groups Projects
Commit 07bb70d8 authored by Bill Welliver's avatar Bill Welliver
Browse files

add capture support to Regexp.PCRE.replace()

parent ba436714
No related branches found
No related tags found
No related merge requests found
...@@ -108,6 +108,9 @@ class Plain ...@@ -108,6 +108,9 @@ class Plain
//! callbacks and replacements will be from the first occurance, //! callbacks and replacements will be from the first occurance,
//! not from the last as in Regexp.Builtin.replace. //! not from the last as in Regexp.Builtin.replace.
//! //!
//! if with is a function, the first argument will be the total match
//! string, and the subsequent arguments will contain any submatches
//!
//! example: //! example:
//! > Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka"); //! > Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka");
//! Result: "agurka-gurka-fooagurka" //! Result: "agurka-gurka-fooagurka"
...@@ -117,27 +120,52 @@ class Plain ...@@ -117,27 +120,52 @@ class Plain
//! "boom" //! "boom"
//! "badoom" //! "badoom"
//! Result: "agurka-gurka-fooagurka" //! Result: "agurka-gurka-fooagurka"
string replace(string subject,string|function(string:string) with) //!
//! example:
//!
//!> Regexp.PCRE("([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})")
//! ->replace("foo@bar.org",
//! lambda(string whole, string user, string loc, string domain)
//! { return user + " from " + loc + " dot " + domain; }
//! );
//! (4) Result: "foo from bar dot org"
string replace(string subject,string|function with, mixed|void ... args)
{ {
int i=0; int i=0;
String.Buffer res = String.Buffer(); String.Buffer res = String.Buffer();
for (;;) for (;;)
{ {
array(int)|int v=exec(subject,i); array(int)|int v=exec(subject,i);
if (intp(v) && !handle_exec_error([int]v)) break; if (intp(v) && !handle_exec_error([int]v)) break;
if (v[0]>i) res->add(subject[i..v[0]-1]); if (v[0]>i) res+=subject[i..v[0]-1];
if (stringp(with)) res->add(with); if
else res->add(with(subject[v[0]..v[1]-1])); (stringp(with)) res+=with;
else
if (i!=v[1]) i=v[1]; else res->add(subject[i..i++]); {
array substrings = ({});
if(sizeof(v)>2)
{
int c = 2;
do
{
substrings += ({ subject[v[c]..(v[c+1]-1)] });
c+=2;
}
while(c<= (sizeof(v)-2));
} }
res->add(subject[i..]); res += with(subject[v[0]..v[1]-1], @substrings, @args);
}
i=v[1];
}
return (string)res; res+=subject[i..];
return res->get();
} }
//! replace one (first) occurance of a pattern in a subject //! replace one (first) occurance of a pattern in a subject
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment