Maruay
Maruay

Reputation: 11

How do I remove specific character before and after single quote using regex

I have a text string with single quotes, I'd like to remove the parenthesis before and after that single quotes by using regular expression. Could anyone suggest me Thank you.

For example, I have (name equal '('John')') the result that I expect is name equal '('John')'

Upvotes: 0

Views: 491

Answers (3)

Code Wines
Code Wines

Reputation: 241

// Using Regex

string input = "(name equal '('John')')";
Regex rx = new Regex(@"^\((.*?)\)$");

Console.WriteLine(rx.Match(input).Groups[1].Value);

// Using Substring method

String input= "(name equal '('John')')";
var result = input.Substring (1, input.Length-2);

Console.WriteLine(result); 

Result:

name equal '('John')'

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31721

Use negative look behind (?<! ) and negative look ahead (?! ) which will stop a match if it encounters the ', such as

(?<!')\(|\)(?!')

The example explains it as a comment:

string pattern =
@"
(?<!')\(     # Match an open paren that does not have a tick behind it
|            # or
\)(?!')      # Match a closed paren tha does not have tick after it
";

var text = "(name equal '('John')')";

 // Ignore Pattern whitespace allows us to comment the pattern ONLY, does not affect processing.
var final = Regex.Replace(text, pattern, string.Empty, RegexOptions.IgnorePatternWhitespace);

Result

name equal '('John')'

Upvotes: 0

yv989c
yv989c

Reputation: 1553

Try this:

var replaced = Regex.Replace("(name equal '('John')')", @"\((.+?'\)')\)", "${1}");

The Regex class is in the System.Text.RegularExpressions namespace.

Upvotes: 0

Related Questions