首页 > 解决方案 > 为文本准备正则表达式

问题描述

我有一段文字:

"text 1

Sentence 1."*"the (1)
 /ðiː/

Sentence 1 Translated."
"text 2

Sentence 2."*"of (2)
 /əv/

Sentence 2 Translated."
"Text 3

Sentence 3!"*"and (3)
 /ænd/

Sentence 3 Translated!"

如何在这样的划分中获取值从"最近的" 获取它们全部作为一个集合

"text 1

Sentence 1."*"the (1)
 /ðiː/

Sentence 1 Translated."

我尝试了这个,但不起作用:

"(.*?)""

标签: c#regex

解决方案


从您的示例字符串来看,您需要从"一行中的第一个字符到"结束一行的第一个字符中获取子字符串。

如果您在单个变量中包含文本,例如text,您可以使用

var results = Regex.Matches(text, @"(?sm)^("".*?"")\r?$")
        .Cast<Match>()
        .Select(m => m.Groups[1].Value);

查看正则表达式演示

图案细节

  • (?sm)-RegexOptions.Singleline并且RegexOptions.Multiline
  • ^- 一行的开始
  • ("".*?"")- 第 1 组:",任何 0+ 个字符,但尽可能少,以及"
  • \r?- 一个可选的 CR(因为$在 CR 之前不匹配)
  • $- 行结束。

推荐阅读