简体   繁体   English

如何从字符串中删除单词?

[英]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" . 例如:对于输入"car wheels_(four) klaxon" ,结果应为"car klaxon"

Can someone give me an example that would accomplish this? 有人可以给我一个例子来实现这一目标吗?

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: 在C#中,正则表达式可以像这样使用:

    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. 我不太确定VB的翻译方式,但希望您能弄清楚。

Slightly different: 稍微不一样:

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

It works like this: 它是这样的:

yourfile: 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

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. 如果速度不是问题,并且您想避免使用过于复杂的正则表达式,则可以使用String.Split on“”创建一个“ words”数组,遍历每个单词,将其中的任何String ..包含“(”空字符串,然后使用String.Join和分隔符“”获得结果。

Sorry can't send the codez, don't have a VB.NET compiler on hand. 抱歉,无法发送代码,没有手头的VB.NET编译器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM