Eduardo Elias
Eduardo Elias

Reputation: 1760

How to create a regex expression on Delphi to remove brackets and quotes

I never used TPerlRegEx before and it is my first time for regex expressions.

I am looking for a small example using TPerlRegEx in Delphi Xe2 to remove the brackets and quotes as follows:

input string:

["some text"]

result:

some text

single line, no nested brackets or quotes. I have used Regexbuddy to create and test the regex however it is not giving me the result.

Upvotes: 2

Views: 6727

Answers (2)

Ken White
Ken White

Reputation: 125728

This works in Regex Buddy:

Regex:

\["(.+?)"\]

Replace:

$1

Use like this:

var
  RegEx: TPerlRegEx;
begin
  RegEx := TPerlRegEx.Create(nil);
  try
    Regex.RegEx := '\["(.+?)"\]';
    Regex.Subject := SubjectString;  // ["any text between brackets and quotes"]
    Regex.Replacement := '$1';
    Regex.ReplaceAll;
    Result := Regex.Subject;
  finally
    RegEx.Free;
  end;
end;

How it works:

Match the character "[" literally «\[»
Match the character """ literally «"»
Match the regular expression below and capture its match into backreference number 1 «(.+?)»
   Match any single character that is not a line break character «.+?»
      Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
Match the character """ literally «"»
Match the character "]" literally «\]»


Created with RegexBuddy

Upvotes: 5

Rob Kennedy
Rob Kennedy

Reputation: 163317

Examples abound, including one in the documentation, so I assume the question is really about what values to assign to which properties to get the specific desired output.

Set the RegEx property to the regular expression that you want to match, and set Replacement to the value you want the matched sequences to be replaced with. One way might be to set RegEx to \[|\]|" and Replacement to the empty string. That will remove all brackets and quotation marks from anywhere in the string.

To instead remove just the pairs of brackets and quotation marks that surround the string, try setting RegEx to ^\["(.*)"\]$ and Replacement to \1. That will match the entire string, and then replace it with the first matched subexpression, which excludes the four surrounding characters. To turn a string like ["foo"] ["bar"] into foo bar, then remove the start and end anchors and add a non-greedy qualifier: \["(.*?)"\].

Once you've set up the regular expression and the replacement, then you're ready to assign Subject to the string you want to process. Finally, call ReplaceAll, and when it's finished, the new string will be in Subject again.

Upvotes: 2

Related Questions