如何定义Regex以从字符串中删除[xx]xxxxx[arch]xxx



我有一个复杂的正则表达式需要实现,非常感谢您的建议。在这里,我将举一些例子,因为这可能是最容易解释的方法:

之前:

[10][pref]
insufficient; incomplete; half-baked; half-hearted; perfunctory
[11][n][arch]
cash
[12][n][abbr]
tipsiness

之后

[10][pref]
insufficient; incomplete; half-baked; half-hearted; perfunctory
[12][n][abbr]
tipsiness

之前

[1][pn][uk]
this (indicating an item near the speaker, the action of the speaker, or the current topic)
[2][pn][hum]
this person (usu. indicating someone in one's in-group)
[3][adv]
now
[4][pn][arch]
here
[5][pn][arch]
I (me)
[6][adv][arch]
certainly

之后

[1][pn][uk]
this (indicating an item near the speaker, the action of the speaker, or the current topic)
[2][pn][hum]
this person (usu. indicating someone in one's in-group)
[3][adv]
now

所以我想做的是删除所有实例:

[xx]xxxxx[arch]xxx

其中搜索字符串的开头是括号中的数字,其中字符串中间有一个[arch],搜索字符串的结尾是下一个术语的"["或字符串的结尾。

我希望得到的是Regex的建议,比如这样:

regex = new Regex(@"(n  )?[arch]*]");

然后我可以使用:

regex.Replace(item.JmdictMeaning, "")

您可以使用

(?m)^[d+](?:[[^][]*])*[arch].*(?:r?n[p{Zs}t].*)*

查看regex演示

  • (?m)-一个DOTALL修饰符
  • ^—线路起点
  • [d+]-一个[,1+位,]
  • (?:[[^][]*])*-[的零个或多个序列,除[]]之外的0个或更多个字符
  • [arch]-一个[arch]子串
  • .*-线路的其余部分
  • (?:r?n[p{Zs}t].*)*-0行或更多行,以水平空白开始,然后有任何0+个字符

不幸的是,.NET正则表达式不支持水平空白的h简写,因此需要[p{Zs}t](p{Zs}本身不匹配制表符(。

最新更新