gpt4 book ai didi

c# - 匹配以 "the"或 "a"开头并以数字结尾的句子的一部分

转载 作者:行者123 更新时间:2023-11-30 18:15:02 25 4
gpt4 key购买 nike

我需要一个标识以下内容的正则表达式:“[the or a] [text] [number]”

例如,在下面的字符串中:

"The foo or the bar 100. A large machine 200." 

我需要一个单独匹配的正则表达式

"the bar 100"
"A large machine 200"

没有匹配

"the foo or the bar 100"

有什么建议吗?

我正在用 C# 实现正则表达式。

最佳答案

我认为这会奏效...虽然可能有一种不那么冗长的方法

\bthe\b(?:(?!\bthe\b).)*?\d+|\ba\b(?:(?!\ba\b).)*?\d+

解释

给定第一部分 \bthe\b(?:(?!\bthe\b).)*?\d+

  • \b 在单词边界断言位置
  • the 按字面意思匹配字符 the
  • \b 在单词边界断言位置

非捕获组 (?:(?!\bthe\b).)*?

  • *? 量词——在零次和无限次之间匹配,尽可能少,根据需要扩展(惰性)

Negative Lookahead (?!\bthe\b) 断言下面的正则表达式不匹配

  • \b 在单词边界断言位置
  • the 按字面意思匹配字符 the
  • \b 在单词边界断言位置

继续

  • . 匹配任何字符(行终止符除外)
  • \d+ 匹配一个数字(等于[0-9])
  • + 量词——在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)

示例

var pattern = @"\bthe\b(?:(?!\bthe\b).)*?\d+|\ba\b(?:(?!\ba\b).)*?\d+";
var input = "The foo or the bar 100. A large machine 200. The transformer 100 and a bridge 200. GufftheGuff guffAguff is not matching 100";

Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

var matches = regex.Matches(input);

foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}

输出

"the bar 100"
"A large machine 200"
"The transformer 100"
"a bridge 200"

Here is a demo for your amusement

You can play with it a bit more here

关于c# - 匹配以 "the"或 "a"开头并以数字结尾的句子的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com