关于正则表达式的难题
我的前台页面如下:
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 697; left: 134px; position: absolute; top: 726px"/>
<asp:TextBox ID="TextBox2" runat="server" Style="z-index: 697; left: 135px; position: absolute; top: 726px"/>
<asp:TextBox ID="TextBox3" runat="server" Style="z-index: 697; left: 132px; position: absolute; top: 726px"/>
我想从前台之文本之中,用正则取得ID:TextBox2它的"left:"属性的值
比如ID:TextBox2的left: 135px,我想从中取得"135",然后把它替换成取它值,应该怎么写正则呢.
之前我的写法如下:
string strPre = @"(?<=<asp:.*?ID=""TextBox2"".*?Style="".*?left:\s{0,1})" + @"(\d*)(?=px.*?"".*?>)";
content = Regex.Replace(content, strPre, new MatchEvaluator(CorrectString), RegexOptions.IgnoreCase);
private string CorrectString(Match match)
{
string matchValue = match.Value;
string strDirection = comboBox1.SelectedItem.ToString();
if (matchValue.Length > 0)
{
if (strDirection == "下" || strDirection == "右")
{
matchValue = Convert.ToString(int.Parse(matchValue) + int.Parse(textBox1.Text.Trim()));
}
else
{
matchValue = Convert.ToString(int.Parse(matchValue) - int.Parse(textBox1.Text.Trim()));
}
}
return matchValue;
}
但不仅会取到TextBox2的值,还会把TextBox3的值也取出来,明明有加非贪婪符"?",怎么表现出来的还是贪婪的呢?
------解决方案--------------------C# code
string tempStr = File.ReadAllText(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312"));//读取txt
string pattern = @"(?i)(?<=<asp:TextBox[^>]*?ID=(['""]?)TextBox2(['""]?)[^>]*?Style=(['""]?)[^'""]*?left:\s*?)\d+";
string result = Regex.Replace(tempStr, pattern,"200");
------解决方案--------------------
Regex reg = new Regex(@"(?is)(?<=<asp[^>]*?TextBox2[^>]*?left:.?)[\d]+(?=px)");
------解决方案--------------------