I want to search keyword stored in variable kw
in large length text and find the FIRST position at which keyword is found . Below code doesn't do EXACT keyword match .
if (webData.IndexOf(kw, StringComparison.OrdinalIgnoreCase) != -1)
{
found = true;
int pos = webData.IndexOf(kw, StringComparison.OrdinalIgnoreCase);
}
how to do it using regex ?
Match match = Regex.Match(webData, @"^kw$", RegexOptions.IgnoreCase);
if (match.Success)
{
int pos = //Matching position
}
You can do
Match match = Regex.Match(webData, @"\b"+Regex.Escape(kw)+@"\b", RegexOptions.IgnoreCase);
if (match.Success)
{
int pos = match.Index;
}
For exact match you need to use boundary represented by \\b
More info here
The Match
will have an Index
property doing just what you want:
Match match = Regex.Match(webData, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
int pos = match.Index;
}
Index - The position in the original string where the first character of the captured substring is found. (Inherited from Capture.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.