开发者

C# Regex.Replace

this is my Set of string inside richtextbox1..

/Category/5
/Category/4
/Category/19
/Category/22
/Category/26
/Category/27
/Category/24
/Category/3
/Category/1
/Category/15
http://example.org/Category/15/noneedtoadd

i want to change all the starting "/" with some url like "http://example.com/"

output:

http://example.com/Category/5
http://example.com/Category/4
http://example.com/Category/19
http://example.com/Category/22
http://example.com/Category/26
http://example.com/Category/27
http://example.com/C开发者_运维技巧ategory/24
http://example.com/Category/3
http://example.com/Category/1
http://example.com/Category/15
http://example.org/Category/15/noneedtoadd

just asking, what is the pattern for that? :)


You don't need a regular expression here. Iterate through the items in your list and use String.Format to build the desired URL.

String.Format(@"http://example.com{0}", str);

If you want to check to see whether one of the items in that textbox is a fully-formed URL before prepending the string, then use String.StartsWith (doc).

if (!String.StartsWith("http://")) { 
    // use String.Format 
}


Since you're dealing with URIs, you can take advantage of the Uri Class which can resolve relative URIs:

Uri baseUri = new Uri("http://example.com/");

Uri result1 = new Uri(baseUri, "/Category/5");
// result1 == {http://example.com/Category/5}

Uri result2 = new Uri(baseUri, "http://example.org/Category/15/noneedtoadd");
// result2 == {http://example.org/Category/15/noneedtoadd}


The raw regex pattern is ^/ which means that it will match a slash at the beginning of the line.

Regex.Replace (text, @"^/", "http://example.com/")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜