我几乎有这个答案。我希望匹配冒号和空格后的所有内容。
所以,如果我有这些行
What is your name: Alain
What is your major: Computer Science
我想捕获"Alain"
和"Computer Science"
。
我有这个正则表达式
(?<=:)\s*\w*
它会捕获一个空格,后跟我的名字,它会捕获" Alain"
和" Computer"
。我怎样才能摆脱领先的白色空间?
谢谢!
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以按照上面的建议使用拆分。但是如果你真的必须使用正则表达式,则以下内容适用于你的字符串。
string line1 = "What is your name: Alain";
Regex rgex = new Regex(@"(?<=:\s)(.*)", RegexOptions.Compiled);
Match match = rgex.Match(line1);
if (match.Success)
{
Console.WriteLine("Name= " + match.Value);
}
Console.ReadKey();
答案 2 :(得分:0)
执行此操作的方法可能较少,但这可行
(?<=What is your name: )(.*)(?= What is your major:)|(?<=What is your major: )(.*)
更新
由于它的多线(由Ben Voigt提供)增加了单词边界
(?<=:\s*)\b.*$
示例强>
var pattern = @"(?<=:\s*)\b.*$";
var input = "What is your name: Alain \r\nWhat is your major: Computer Science";
var matches = Regex.Matches(input, pattern, RegexOptions.Multiline);
foreach (var match in matches)
{
Console.WriteLine(match);
}
答案 3 :(得分:0)
也许你可以使用Regex.Split并用冒号分割零个或多个空格:\s*
string[] lines = { "What is your name: Alain" , "What is your major: Computer Science " };
string pattern = @":\s*";
foreach (string str in lines)
{
Console.WriteLine(Regex.Split(str, pattern)[1]);
}