C#正则表达式替换意外的行为 [英] C# regex replace unexpected behavior

查看:154
本文介绍了C#正则表达式替换意外的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 $ displayHeight =800; ,更换任何数字是 800 用int值 y_res

Given $displayHeight = "800";, replace whatever number is at 800 with int value y_res.

resultString = Regex.Replace(
    im_cfg_contents, 
    @"\$displayHeight[\s]*=[\s]*""(.*)"";", 
    Convert.ToString(y_res));

在Python中我会使用应用re.sub和它的工作。在.NET中它取代了整条生产线,而不是匹配的组。

In Python I'd use re.sub and it would work. In .NET it replaces the whole line, not the matched group.

什么是速战速决?

推荐答案

大厦一对夫妇已经公布的答案。零宽度断言允许你做一个普​​通的前pression比赛而不将这些字符在比赛中。通过将串的第一部分中的一组,我们已经从要被替换位数分离它。然后,由该组使用零宽度向后断言我们允许定期EX pression以正常进行,但省略了字符在该组的比赛。同样,我们已放置字符串的最后部分中的一组,并使用零宽度前向断言。 分组构造显示组作为以及断言。

Building on a couple of the answers already posted. The Zero-width assertion allows you to do a regular expression match without placing those characters in the match. By placing the first part of the string in a group we've separated it from the digits that you want to be replaced. Then by using a zero-width lookbehind assertion in that group we allow the regular expression to proceed as normal but omit the characters in that group in the match. Similarly, we've placed the last part of the string in a group, and used a zero-width lookahead assertion. Grouping Constructs on MSDN shows the groups as well as the assertions.

resultString = Regex.Replace(
    im_cfg_contents, 
    @"(?<=\$displayHeight[\s]*=[\s]*"")(.*)(?="";)", 
    Convert.ToString(y_res));

另一种方法是使用以下code。修改到正规的前pression只是放置在一组中的第一部分和在一组的最后部分。然后在替换字符串,我们加回在第一和第三组。不太一样好作为第一种方法,但不是那么糟糕写出$ displayHeight一部分。在MSDN上 MSDN">换人

Another approach would be to use the following code. The modification to the regular expression is just placing the first part in a group and the last part in a group. Then in the replace string, we add back in the first and third groups. Not quite as nice as the first approach, but not quite as bad as writing out the $displayHeight part. Substitutions on MSDN shows how the $ characters work.

resultString = Regex.Replace(
    im_cfg_contents, 
    @"(\$displayHeight[\s]*=[\s]*"")(.*)("";)", 
    "${1}" + Convert.ToString(y_res) + "${3}");

这篇关于C#正则表达式替换意外的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆