【问题标题】:Regular expressions: How to remove all "R.G(*******)" from a string正则表达式:如何从字符串中删除所有“R.G(*******)”
【发布时间】:2013-05-16 13:05:26
【问题描述】:

有几个字符串,我想从这些字符串中删除所有“R.G(**)”。例如:

1、原字符串:

Push("Command", string.Format(R.G("#{0} this is a string"), accID));

结果:

Push("Command", string.Format("#{0} this is a string", accID));

2、原字符串:

Select(Case(T["AccDirect"]).WhenThen(1, R.G("input")).Else(R.G("output")).As("Direct"));

结果:

Select(Case(T["AccDirect"]).WhenThen(1, "input").Else("output").As("Direct"));

3、原字符串:

R.G("this is a \"string\"")

结果:

"this is a \"string\""

4、原字符串:

R.G("this is a (string)")

结果:

"this is a (string)"

5、原字符串:

AppendLine(string.Format(R.G("[{0}] Error:"), str) + R.G("Contains one of these symbols: \\ / : ; * ? \" \' < > | & +"));

结果:

AppendLine(string.Format("[{0}] Error:", str) + "Contains one of these symbols: \\ / : ; * ? \" \' < > | & +");

6 、原字符串:

R.G(@"this is the ""1st"" string.
this is the (2nd) string.")

结果:

@"this is the ""1st"" string.
this is the (2nd) string."

请帮忙。

【问题讨论】:

  • R.G(...) 项目是否总是只存在于一行中?
  • 另外,您是否需要能够应对例如R.G("Hello)World")?
  • 不应该 thiscurrent 示例工作吗?
  • 正则表达式是这个工作的错误工具。一个简单的有状态解析器效果更好。

标签: c# .net regex expression


【解决方案1】:

使用这个,捕获组 0 是您的目标,组 1 是您的替换。

Fiddle

R[.]G[(]"(.*?[^\\])"[)]

作用于你的#2 和#4 字符串的示例以及一个新的边缘情况R.G("this is a (\"string\")")

var pattern = @"R[.]G[(]\""(.*?[^\\])\""[)]";
var str = "Select(Case(T[\"AccDirect\"]).WhenThen(1, R.G(\"input\")).Else(R.G(\"output\")).As(\"Direct\"));";
var str2 = "R.G(\"this is a (string)\")";
var str3 =  "R.G(\"this is a (\\\"string\\\")\")";

var res =  Regex.Replace(str,pattern, "\"$1\"");
var res2 = Regex.Replace(str2,pattern, "\"$1\"");
var res3 = Regex.Replace(str3,pattern, "\"$1\"");

【讨论】:

  • 不客气。像大多数正则表达式一样,它对边缘情况有弱点,所以如果有任何反例,请更新问题。
  • 这个呢:R.G("this is a (string)") -> "this is a (string)" there are () in this string
  • 是的,您添加的第四个将是一个挑战。也许我们可以在捕获组 1 中使用某种前瞻来确保它后面跟着 [^\\]") 或类似的
  • 好的,我让.* 变得懒惰,并确保组书挡不是转义的引号括号序列\")
  • 向前看?我不明白……我觉得你真的很好,如果第4个对你有挑战,我不可能解决它。你能帮我做吗?
【解决方案2】:

试试这个:

var result = Regex.Replace(input, @"(.*)R\.G\(([^)]*)\)(.*)", "$1$2$3");

解释:

(.*)     # capture any characters
R.G\(    # then match 'R.G.'
([^)]*)  # then capture anything that isn't ')'
\)       # match end parenthesis
(.*)     # and capture any characters after

$1$2$3 将您的整个比赛替换为捕获组 1、2 和 3。这有效地删除了不属于这些比赛的所有内容,即“R.G(*)”部分.

请注意,如果您的字符串在某处包含“R.G”或右括号,您会遇到问题,但根据您的输入数据,这可能会足够好。

【讨论】:

  • 这将在示例 2 中失败,因为您使用的是 .* 书挡
猜你喜欢
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2021-10-13
  • 2021-01-17
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多