开发者

Simple Regex c#, Replace and Split Question

I am trying to remove " from a string using Regex.

I am receiving a string into a method, I would like to take the string and split it up into the words that are in the string.

My Code is below, hopefully you can see what I am doing.

The problem I am having is trying to tell Regex that " is what I would like to remove. I have tried numerous ways: I have searched Google for a answer and have had to resort to here.

search_string looks like this: blah="blah" la="la" ta="ta" and in the end I want just the blah blah la la ta ta.

public blahblah blahblah(blah blah, string search_str开发者_JAVA百科ing)
        {                
            Regex r = new Regex(@"/"+");

            string s3 = r.Replace(search_string, @" ");

            Regex r2 = new Regex(" ");
            Regex r3 = new Regex("=");

            string[] new_Split = { };

            string[] split_String = r2.Split(s3);


            foreach (string match in split_String)
            {
                new_Split = r3.Split(match);

            }

            //do blahblah stuff with new_Split[1] .. etc
            // new_Split[0] should be blah and new_Split[1] should 
            //     be blah with out "", not "blah"


            return blah_Found;


Just use:

myString = myString.Replace( "\"", String.Empty );

[Update]

The String.Empty or "" is not a space char. You wrote this

blah="blah" la="la" ta="ta"

you want to convert to

blah blah la la ta ta

So you have white spaces anyway. If you want this:

blahblahlalatata

you need to remove them too:

myString = myString.Replace( "\"", String.Empty ).Replace( " ", String.Empty );

for '=' do it again, and so on...

You need to be more precise in your questions.


As a quick thought - and barking maybe up entirely the wrong tree, but wouldnt you want something like

Regex r = new Regex("(\".*\")");

eg, a reg expression of ".*"


This is one way to do it. It will Search for anything in that form: SomeWord="somethingelse"
and replace it with SomeWord somethingelse

var regex = new Regex(@"(\w+)=\""(.+)\""");
var result = regex.Replace("bla=\"bla\"", "$1 $2");


I can't help you with Regex.
Anyway if you only need to remove = and " and split words you could try:

string[] arr = s
    .Replace("="," ")
    .Replace("\""," ")
    .Split(new string[1] {" "}, StringSplitOptions.RemoveEmptyEntries);


I did it in 2 passes

string input = "blah=\"blah\" la=\"la\" ta=\"ta\"";

//replace " and = with a space
string output = Regex.Replace(input, "[\"=]", " ");
//condense the spaces
output = Regex.Replace(output, @"\s+", " ");

EDIT:
Treating " and = differently as per comment.

string input = "blah=\"blah\" la=\"la\" ta=\"ta\"";

//replace " and = with a space
string output = Regex.Replace(input, "\"", String.Empty);
output = Regex.Replace(output, "=", " ");  

Clearly regex is a bit overkill here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜