Removing brackets
Consider:
string value = "htt开发者_如何学运维p://url.com/index?foo=[01234]&bar=1";
I need to remove the [
]
, brackets.
I tried
value = value.Replace("[01234]", "1234");
and this didn't work.
Should I look into a regular expression?
EDIT
I can't do only [
or ]
because string can contain more than one, [
or ]
. I just want foo = [blah]
to be replaced with foo = blah
**.
You could just do -
value = value.Replace("[", "").Replace("]", "");
EDIT
Or with a regex (not tested) -
Regex regexObj = new Regex(@"(foo=)\[([0-9A-Za-z]+)\]");
value = value.Replace(subjectString, "$1$2");
value = value.Replace("[","").Replace("]","");
You probably don't need regex. A simple string replace would do it:
using System;
using System.Web;
class Program
{
static void Main()
{
string value = "http://url.com/index?foo=[01234]&bar=1";
var uriBuilder = new UriBuilder(value);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["foo"] = query["foo"].Replace("[", "").Replace("]", "");
uriBuilder.Query = query.ToString();
value = uriBuilder.ToString();
Console.WriteLine(value);
}
}
This will ensure that only the brackets of the foo
parameter will be removed.
I'd go with a Regex:
var value = "http://url.com/index?foo=[01234]&bar=1";
value = Regex.Replace(value, "foo=\\[(.*?)\\]","foo=$1");
精彩评论