Skip to main content
 首页 » 编程设计

c#之在 C# 中使用正则表达式更改字符串(基于 ActionScript 函数)

2024年02月24日28kerrycode

我有一些 ActionScript 代码使用正则表达式拆分字符串并让我在拆分位置添加内容。

// AS3 Code 
function formatTweetText(tweet:String ):String 
    { 
        var regUrl:RegExp = /http:\/\/\S+/g; 
        var _text:String = " "+ tweet + " ";                             
        _text = _text.replace(regUrl, '<font color="#666666"> <a href="$&" target="_blank">$&</a></font>'); 
        _text = _text.substr(1, _text.length-2); 
            return _text; 
} 

我正在尝试找到与上述函数等效的 C#

这样做是为您提供整个文本值,并在正则表达式找到匹配项的位置插入替换文本。

例如:

var text:String = "Hello there http://www.url.com"; 

会变成

var newString:String =  "hello there <font color="#666666"> <a href="http://www.url.com" target="_blank">http://www.url.com</a></font>" 

请您参考如下方法:

using System.Text.RegularExpressions; 
 
private string formatTweetText(string tweet) 
{ 
    string newText = " " + Regex.Replace(tweet, "/http:\/\/\S+/g", "Replacement String") + " "; 
    return newText.SubString(1, (newText.Length - 2)); 
}