如果正则表达式没有出现在字符串的开头,则不要匹配它
DO not match regex if it does not occur at the start of the string
我正在尝试编写一个正则表达式来匹配恰好包含 3 个单词的句子,每个单词之间有一个 space,中间的单词是 "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"
我做错了什么?
您需要添加行锚点 (^
) 的开头。
string queryFormat = @"^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$
只需添加 ^
起始锚点,使其严格匹配 3 个词,而不是部分匹配。
^ assert position at start of a line
查看演示。
我正在尝试编写一个正则表达式来匹配恰好包含 3 个单词的句子,每个单词之间有一个 space,中间的单词是 "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"
我做错了什么?
您需要添加行锚点 (^
) 的开头。
string queryFormat = @"^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$
只需添加 ^
起始锚点,使其严格匹配 3 个词,而不是部分匹配。
^ assert position at start of a line
查看演示。