简体   繁体   中英

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')'

// 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')'

Try this:

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

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

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')'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM