从包含问题的字符串中删除子字符串

时间:2016-07-25 10:21:57

标签: c# string substring

我想从字符串中删除包含问题的所有子字符串。
例如,
原始字符串:   你好,你好吗?你在做什么?这件事情很完美。
结果: 你好这件事是完美的。
我想删除所有从 what-when-where-which-how-etc 开始的子字符串,最后是 ?(问号) 。(点)

 Regex questions = new Regex("what|why|when|How|where|who|which|whose|whom");
 string propertyValue = "Hello How are you? what are you doing? this thing is perfect.";
 if (questions.IsMatch(propertyValue))
        {
            int index1 = propertyValue.IndexOf("what");
            int index2 = propertyValue.IndexOf('?');
            int count = index2 - index1;
            propertyValue = propertyValue.Remove(index1,count+1);

        }

我试过这个,但我不明白如何获得多个值的索引,因为我有一个问题列表。

2 个答案:

答案 0 :(得分:0)

相当简单:

使用非捕获组来查找单词/ {/ 1}}

的方式/内容/位置等

然后任意数量的字符不是(?:how|what|when|where|whose)?,后跟其中任何一个:.

在前面添加一个或多个空格字符以匹配,你应该好好去:

'[^\?\.]*(?:\?|\.)

输出string input = "Hello How are you? what are you doing? this thing is perfect. "; string pattern = @"\s+(?:how|what|when|where|whose)[^\?\.]*(?:\?|\.)"; string result = Regex.Replace(input, pattern, "", RegexOptions.IgnoreCase); Console.WriteLine(result);

答案 1 :(得分:0)

使用正则表达式:

String str = "Hello How are you? what are you doing? this thing is perfect.";

Regex rgx = new Regex(@"(How|What|When|Where)(.*?)(\?|\.)", RegexOptions.IgnoreCase);
str = rgx.Replace(str, "").Replace("  ", " ");

正则表达式模式如下:

匹配以(howwhat或等)开头的字符串,后跟任何字符,以?.

结尾

第二个Replace是省略操作产生的额外空格..