以类似字符串的形式
[\\\x2286400000\\\x22,\\\x22604800000\\\x22,2.0]\\n,null,1]\\n\x22,\x22mnr_crd\x22:\x221\x22,\x22msg_dsc\x22:\x22From your Internet address\x22,\x22msg_dvl\x22:\x22Reported by this computer\x22,\x22msg_err\x22:\x22Location unavailable\x22,\x22msg_gps\x22:\x22Using GPS\x22,\x22msg_unk\x22:\x22Unknown\x22,\x22msg_upd\x22:\x22Update location\x22,\x22msg_use\x22:\x22Use precise location\x22,\x22uul_text\x22:\x22Home Location\x22}
我正在尝试将Home location
与正则表达式进行匹配
(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})
这是整个代码:
string locationRegExpression = "(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})";
Regex locationMmatch = new Regex(locationRegExpression, RegexOptions.Singleline);
MatchCollection locationCollection = Regex.Matches(locationHtmlContent,locationRegExpression);
// lblCurrentLocation.Text = "Location: " + locationCollection[0];
MessageBox.Show(locationCollection[0].ToString());
在在线正则表达式测试器站点中,上面的正则表达式代码与下面的html代码可以正常工作,但是如果我在C#win窗体中使用相同的正则表达式。其给出0个结果。有想法吗?
Whole text在这里。
答案 0 :(得分:2)
似乎您要匹配包含文字\x22
子字符串的字符串中的单个子字符串。您需要确保匹配一个文字\
符号,也就是说,您需要在模式中使用两个文字反斜杠。最好使用逐字字符串文字(为避免转义,请使用@"..."
),并且足以使用Regex.Match
方法:
string locationRegExpression = @"(?<=:\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22)(.+?)(?=\\x22})";
Regex locationMmatch = new Regex(locationRegExpression, RegexOptions.Singleline);
Match locationMatch = locationMmatch.Match(locationHtmlContent);
if (locationMatch.Success)
{
MessageBox.Show(locationMatch.Value);
}
请注意,在此处使用捕获组而不是将lookbehind和lookahead组合在一起可能会“更简单”:
@":\\x22Use precise location\\x22,\\x22uul_text\\x22:\\x22(.+?)\\x22}"
然后
MessageBox.Show(locationMatch.Groups[1].Value)