gpt4 book ai didi

c# - 如果正则表达式没有出现在字符串的开头,则不要匹配它

转载 作者:行者123 更新时间:2023-11-30 20:45:36 26 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来匹配恰好包含 3 个单词的句子,每个单词之间有一个空格,中间的单词是“is”。

例如,如果输入是,则正则表达式应该是匹配的

"This is good"

如果输入字符串是,则不应该匹配

"This this is good"

这就是我现在正在尝试的:

string text = "this is good";
string queryFormat = @"(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
Regex pattern = new Regex(queryFormat, RegexOptions.IgnoreCase);
Match match = pattern.Match(text);

var pronoun = match.Groups["pronoun"].Value; //Should output "this"
var adjective = match.Groups["adjective"].Value; //should output "good"

上面的正则表达式匹配字符串“this this is good”

我做错了什么?

最佳答案

^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$

只需添加 ^ 开始 anchor ,使其严格匹配 3 个单词,而不是部分匹配。

^ assert position at start of a line

查看演示。

https://regex101.com/r/tX2bH4/18

关于c# - 如果正则表达式没有出现在字符串的开头,则不要匹配它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967266/

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