Author Topic: RegExpReplace problem  (Read 551 times)

0 Members and 1 Guest are viewing this topic.

Offline tk

  • Soldier
  • **
  • Posts: 235
RegExpReplace problem
« on: April 23, 2009, 11:26:47 am »
Quote
If RegularExpression contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

//...
Text:='abc def';
writeln(
  RegExpReplace('(\w+) (\w+)',Text,'\\2 \\1',true)
);
//...
I would like to get 'def abc' instead of 'abc def' but the RegExpReplace returns '\2 \1'. I tried many ways but it doesn't work correctly. What is the syntax of the regExpReplace from the scriptcore?

Offline CurryWurst

  • Camper
  • ***
  • Posts: 265
    • Soldat Global Account System
Re: RegExpReplace problem
« Reply #1 on: April 23, 2009, 12:02:20 pm »
Sorry, but I guess the ScriptCore is unable to deal with that.
I asked EnEsCe a few times about that, but never got a really answer to the problem.
Soldat Global Account System: #soldat.sgas @ quakenet

Offline JFK

  • Camper
  • ***
  • Posts: 255
    • My TraxInSpace Account
Re: RegExpReplace problem
« Reply #2 on: April 23, 2009, 02:29:23 pm »
afaik that whole part about the substrings has never worked.

You could solve this problem by using my RegExpExtract function. Instead of removing patterns it will return them.

Code: [Select]
//Opposite of RegExpReplace, returns all matches as one string.
//Needs xsplit!
function RegExpExtract(const Pattern: string; const Source: string): string;
var
a: string;
i: integer;
s: array of string;
begin
  if RegExpMatch(Pattern, Source) then begin
a := RegExpReplace(Pattern, Source, '@@CUT@@', true)+'@@CUT@@';
    a := RegExpReplace('[\\\?\*\(\)\{\}\[\]\|\+\$\^]',a, '\.', true);
    s := xsplit(a, '@@CUT@@');
    result := Source;
    for i:=0 to (getArrayLength(s)-2) do   
  if s[i] <> '' then
    result := RegExpReplace(s[i], result, '', true);
  end;
 end;

In this case:
Code: [Select]
result := RegExpExtract('\w+$', Text)+' '+RegExpExtract('^\w+', Text)

^ and $ symbolize the start and end of an string.
Using the extract function might make it a bit easier then using only RegExpReplace, but you don't actually need it. However it might give you an example how to create your own regexp function that WILL return substrings the way you like it.
Come join: EliteCTF
Listen to: My Music

Offline CurryWurst

  • Camper
  • ***
  • Posts: 265
    • Soldat Global Account System
Re: RegExpReplace problem
« Reply #3 on: April 23, 2009, 02:54:29 pm »
Simple and efficient. Good job JFK!
Soldat Global Account System: #soldat.sgas @ quakenet