正则表达式来消除周围的某些字符不需要的空格 [英] Regex to remove unwanted spaces around certain characters

查看:196
本文介绍了正则表达式来消除周围的某些字符不需要的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从JavaScript文件中删除一些不需要的空白,并使用C#和正则表达式合并文件,它们被发送到客户端之前。我有一个 JavascriptHandler 处理的.js文件,它工作正常。这是我使用打包JavaScript的功能。

I'm trying to remove some unwanted whitespace from JavaScript files, and combine files using C# and Regex, before they are sent to the client. I have a JavascriptHandler to handle the .js files, which works fine. This is the function that I'm using to "pack" the JavaScript.

private string PackJs(string file)
{
    string text = System.IO.File.ReadAllText(JSFolder + file);

    //replace any combination of unwanted whitespace with a single space
    text = Regex.Replace(text, @"[\r\n\s]+", " ");

    //Can I get this to match +, =, -, etc?
    text = Regex.Replace(text, @"( [=] )", "="); 

    //more regular expressions here, when I get round to it

    return text;
}

我的第二个前pression目前将取代=与=。我想指定更多的字符和关键字,可以有从两侧取出空间。

My second expression currently will replace " = " with "=". I'd like to specify more characters and keywords that can have the spaces removed from either side.

我如何寻找这种在常规EX pression,然后向后引用,在替换字符或关键字?

How do I search for this in the regular expression, then back-reference that character or keyword in the replacement?

谢谢

推荐答案

[] 把你的字

var input = "c = a + b";
var result = Regex.Replace(input, @"\s([=+])\s", "$1");

结果将是: C = A + B

这篇关于正则表达式来消除周围的某些字符不需要的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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