[英]DO not match regex if it does not occur at the start of the string
我正在尝试编写一个正则表达式来匹配一个句子,该句子正好与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 good”
我究竟做错了什么?
您需要添加行锚的开头( ^
)。
string queryFormat = @"^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$
Jsut添加^
起始锚以使其严格匹配3个单词,而不是部分匹配。
^ assert position at start of a line
参见演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.