我有一个带单引号的文本字符串,我想通过使用正则表达式删除单引号之前和之后的括号。谁能建议我谢谢你。
例如,我有(name equal '('John')')
结果,我期望是name equal '('John')'
//使用Regex
string input = "(name equal '('John')')";
Regex rx = new Regex(@"^\((.*?)\)$");
Console.WriteLine(rx.Match(input).Groups[1].Value);
//使用Substring方法
String input= "(name equal '('John')')";
var result = input.Substring (1, input.Length-2);
Console.WriteLine(result);
结果:
name equal '('John')'
试试这个:
var replaced = Regex.Replace("(name equal '('John')')", @"\((.+?'\)')\)", "${1}");
Regex
类位于System.Text.RegularExpressions
名称空间中。
使用(?<! )
后面的负面看法和负面向前看(?! )
,如果它遇到'
将阻止比赛,例如
(?<!')\(|\)(?!')
该示例将其解释为注释:
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);
结果
名字相等'('John')'