C# 使用';的正则表达式标识符和分隔符:';象征
我想在两个C# 使用';的正则表达式标识符和分隔符:';象征,c#,asp.net,regex,C#,Asp.net,Regex,我想在两个':'字符之间分隔字符串 例如,如果输入是“mypage google wax:press:-happy”,则我希望“press”退出 可以假定输入不包含任何数字字符。使用正则表达式的原因是什么,而不仅仅是: string[] bits = text.Split(':'); 假设我正确理解了你的问题。。。我一点也不确定。无论如何,根据您真正想要做的事情,这可能对您很有用…如果您总是使用{stuffIDontWant}:{stuffIWant}:{MoreSuffidontWant}格
':'
字符之间分隔字符串
例如,如果输入是“mypage google wax:press:-happy”
,则我希望“press”
退出
可以假定输入不包含任何数字字符。使用正则表达式的原因是什么,而不仅仅是:
string[] bits = text.Split(':');
假设我正确理解了你的问题。。。我一点也不确定。无论如何,根据您真正想要做的事情,这可能对您很有用…如果您总是使用
{stuffIDontWant}:{stuffIWant}:{MoreSuffidontWant}
格式的字符串,那么string.Split()
是您的答案,而不是Regex
要检索中间值,请执行以下操作:
string input = "stuffIDontWant:stuffIWant:moreStuffIDontWant"; //get your input
string output = "";
string[] parts = input.Split(':');
//converts to an array of strings using the character specified as the separator
output = parts[1]; //assign the second one
return output;
正则表达式很适合进行模式匹配,但是,除非您特别查找单词
press
,String.Split()
,否则更好地满足这一需求。如果您希望在正则表达式中使用它:
string pattern = ":([^:]+):";
string sentence = "some text :data1: some more text :data2: text";
foreach (Match match in Regex.Matches(sentence, pattern))
Console.WriteLine("Found '{0}' at position {1}",
match.Groups[1].Value, match.Index);
为什么输出是“按”?它到底应该做什么?你谈论“分离”你的字符串,但不是你真正的意思…(试图澄清这个问题,不确定我是否无意中改变了它的意思。)