Sein Kraft
Sein Kraft

Reputation: 8815

How can I remove a word from string?

I have a string which contains words with parentheses. I need to remove the whole word from the string.

For example: for the input, "car wheels_(four) klaxon" the result should be, "car klaxon".

Can someone give me an example that would accomplish this?

Upvotes: 1

Views: 3219

Answers (3)

Mark Byers
Mark Byers

Reputation: 838256

You can do this with regular expressions. The regular expression you need is:

"\s?\S+[()]\S+\s?"

This removes any word containing either ( or ) or both, and removes both the word and collapses the surrounding whitespace. The match should be replaced with a single space.

In C# the regular expression could be used like this:

    string s = "car wheels_(four) klaxon";
    s = Regex.Replace(s, @"\s?\S*[()]\S*\s?", " ");

I'm not entirely sure of the VB translation for this, but hopefully you can figure it out.

Upvotes: 6

Federico Giorgi
Federico Giorgi

Reputation: 10735

Slightly different:

sed "s/\s\+\S*(.\+)\S*\s\+/ /g" yourfile

It works like this:

yourfile:

car wheels_(four) klaxon
ciao (wheel) hey
foo bar (baz) qux
stack overflow_(rulez)_the world

transformed in:

car klaxon
ciao hey
foo bar qux
stack world

Upvotes: 1

Phil
Phil

Reputation: 183

If speed isn't an issue and you want to avoid overcomplicated regular expressions, you can use String.Split on " " to create an array of "words", iterate through each word, replace any that String.Contains "(" with an empty string, then use String.Join with a separator of "" to get your results.

Sorry can't send the codez, don't have a VB.NET compiler on hand.

Upvotes: 0

Related Questions