【问题标题】:c# regex only first match in each sentencec# 正则表达式只匹配每个句子的第一个匹配项
【发布时间】:2020-01-08 15:35:02
【问题描述】:

我几乎有了我的正则表达式,但后来我遇到了一个我无法解决的问题。

句子:

oListView.sTranslatedPrintHeader = Dictionary.gsTranslate(oClientInfo, "Lastschriftenstapel") & " " & DataMethods.gsGetDBValue(oClientInfo, "BatchDesc", "tdDebitAdviceBatches", "BatchID=" & lBatchID)

Response.Write(Dictionary.gsTranslate(oClientinfo,"Es konnten keine Befehle in der Auswahl dargestellt werden,
" & _ "das Design kann trotzdem modifiziert werden。"))

正则表达式:

(?<=[D-d]ictionary\.gs[T-t]ranslate.*?, ?)( ?")((.|\n|\r)*?"\))

示例和输出:https://regexr.com/4rpfj

所以我的第一个匹配是好的,但是我的正则表达式并没有在那个句子中停止而是继续然后匹配

“BatchDesc”、“tdDebitAdviceBatches”、“BatchID=" & lBatchID)

Response.Write(Dictionary.gsTranslate(oClientinfo,"Es konnten keine Befehle in der Auswahl dargestellt werden,
" & _ "das Design kann trotzdem modifiziert werden。")

我想要什么匹配

"Lastschriftenstapel")

"Es konnten keine Befehle in der Auswahl dargestellt werden,<br>" & _ "das Design kann trotzdem modifiziert werden.")

小提示:有一个包含多个匹配项的完整文件。所以我不想要文本中的第一个匹配,我想要每个 Dictionary.gsTranslate 之后的第一个匹配。

【问题讨论】:

  • (?&lt;=(?i)dictionary\.gstranslate(?-i)\([^)]+, *)"[^)]+" 适合你吗?
  • @ctwheels 完美!谢谢
  • 我将其转换为答案

标签: c# regex


【解决方案1】:

您可以使用以下正则表达式:

See regex in use here

(?<=(?i)dictionary\.gstranslate\([^)]+, *)"[^)]+"
# or the following with RegexOptions.IgnoreCase
(?<=dictionary\.gstranslate\([^)]+, *)"[^)]+"

它是如何工作的:

  • (?&lt;=(?i)dictionary\.gstranslate\([^)]+, *) 积极的后视确保以下先于
    • (?i) 启用不区分大小写的标志
    • dictionary\.gstranslate 匹配 dictionary.gstranslate 字面意思(不区分大小写)
    • \( 匹配 ( 字面意思
    • [^)]+ 匹配除) 之外的任何字符一次或多次
    • , * 匹配逗号,然后是任意数量的空格
  • "[^)]+" 匹配",然后匹配除) 之外的任何字符一次或多次,然后匹配"

【讨论】:

  • (?-i) 没有区别,后面没有匹配的字母。
【解决方案2】:

据我所见,\n|\r 允许匹配包含并超越“BatchDesc”...因为下划线字符应该出现换行符继续(根据我在您的文本中看到的)也许这会满足您的需要:

(?<=[D-d]ictionary\.gs[T-t]ranslate.*?, ?)("(.|\_ ?\n|\_ ?\r)*?"(?=\)))

我只是在 \n 和 \r 之前添加了强制下划线。

https://regexr.com/4rrv0

【讨论】:

  • 我收到一个错误:System.ArgumentException: 'parsing "(?&lt;=[D-d]ictionary\.gs[T-t]ranslate.*?, ?")((.|\_ ?\n|\_ ?\r)*?"\))" - Unrecognized escape sequence \_.' 我正在使用 c#,就像我的标签告诉我的那样,有什么解决方法吗?
  • @NielsLucas 对于所有出现的\_,您需要转义它们。将它们更改为\\_
  • @Kit 啊谢谢!我今天晚些时候会尝试,即使我已经有了答案,我也想尝试其他解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 2011-07-30
  • 2020-12-03
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多