我想从字符串中删除包含问题的所有子字符串。
例如,
原始字符串:
你好,你好吗?你在做什么?这件事情很完美。
结果: 你好这件事是完美的。
我想删除所有从 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);
}
我试过这个,但我不明白如何获得多个值的索引,因为我有一个问题列表。
答案 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(" ", " ");
正则表达式模式如下:
匹配以(how
或what
或等)开头的字符串,后跟任何字符,以?
或.
第二个Replace
是省略操作产生的额外空格..