首页 > 解决方案 > 如何定义正则表达式以从字符串中删除 [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[拱门] xxx

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

我希望得到的是这样的正则表达式建议:

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

然后我可以使用:

regex.Replace(item.JmdictMeaning, "")

标签: regex

解决方案


您可以使用

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

查看正则表达式演示

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

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


推荐阅读