简体   繁体   English

如何删除单词,以:sign开头,以:sign结尾,而不是c#中的完整句子

[英]How to remove words starts with : sign and ends with : sign, not a full sentence in c#

I want to remove the words having : sign (Like :word:) in its both side.I have already use a regular expression to remove all between two : sign. 我想删除两侧都带有:符号的单词(Like:word :)。我已经使用正则表达式删除了两个:sign之间的所有单词。 But i need to remove just single words exists between two : sign, not a full sentence (Like :I like to play cricket:). 但是我需要删除两个:符号之间不存在的单个单词,而不是完整的句子(例如:我喜欢打板球:)。

string txt = "Hello, i :want: to remove :some word from: my text";
var output = Regex.Replace(txt, @" ?\:.*?\:", " ");

Expected Output: 预期产量:

Hello, i to remove some word from my text 您好,我要从文字中删除一些单词

the problem is your regex. 问题是您的正则表达式。 try this: 尝试这个:

 var output = Regex.Replace(txt, @":([A-Za-z0-9]*):", "");

In your regex you're using .* this matches any character except newline. 在正则表达式中,您使用的是.*它匹配除换行符以外的任何字符。 Instead I assume you would like any non-whitespace character. 相反,我假设您想要任何非空白字符。 In regex this would be \\S , so in total you would get: 在正则表达式中,这将是\\S ,因此,您总共可以得到:

string txt = "Hello, i :want: to remove :some word from: my text";
var output = Regex.Replace(txt, @" ?\:\S*?\:", " ");

Use character class for matching words in your regex. 使用字符类来匹配正则表达式中的单词。

"\\:\\w\\:"

This will match words surrounded by : on both sides and nothing else. 这将匹配两边用:包围的单词,仅此而已。

我建议这个:

var output = Regex.Replace(txt, @":\w+:", "");

You can find all the words having : sign in its both side But it should not have space 您可以找到所有具有的词:在其两面都签收,但不应有空格

string txt = "Hello, i :want: to remove :some word from: my :test:";
var output = Regex.Replace(txt, @" \:\w+\b(?! )\:", " ");

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

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