在 C# 中使用正则表达式划分字符串
Dividing a string using regular expression in C#
我有一个这样的字符串:
"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000"
如您所见,该字符串由人名和他们的份额组成。可以有任意数量的人(和份额),人名可以由任意数量的单词组成。
如何将这个字符串分成三个这样的字符串:
"John William Doe 250 / 1000"
"Adam Smith 500 / 1000"
"Jane Black 250 / 1000"
我知道我需要使用正则表达式,但我自己做不到。任何帮助表示赞赏。谢谢
([a-zA-Z ]*)*[0-9]* \/ [0-9]*
您首先要查找带有 space 的名称,然后重复这些。
您继续输入数字、斜杠和另一个数字
注意 spaces。
我知道这不是那么难的问题,评论里已经有一些答案了,我还是想贴一下OP的代码:
static void Main(string[] args)
{
string all = @"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000";
Regex r = new Regex(@"(?:\w+\s+)+\d+\s+/\s+\d+");
foreach (Match m in r.Matches(all))
{
Console.WriteLine(m.Groups[0]);
}
Console.ReadLine();
}
我有一个这样的字符串:
"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000"
如您所见,该字符串由人名和他们的份额组成。可以有任意数量的人(和份额),人名可以由任意数量的单词组成。
如何将这个字符串分成三个这样的字符串:
"John William Doe 250 / 1000"
"Adam Smith 500 / 1000"
"Jane Black 250 / 1000"
我知道我需要使用正则表达式,但我自己做不到。任何帮助表示赞赏。谢谢
([a-zA-Z ]*)*[0-9]* \/ [0-9]*
您首先要查找带有 space 的名称,然后重复这些。
您继续输入数字、斜杠和另一个数字
注意 spaces。
我知道这不是那么难的问题,评论里已经有一些答案了,我还是想贴一下OP的代码:
static void Main(string[] args)
{
string all = @"John William Doe 250 / 1000 Adam Smith 500 / 1000 Jane Black 250 / 1000";
Regex r = new Regex(@"(?:\w+\s+)+\d+\s+/\s+\d+");
foreach (Match m in r.Matches(all))
{
Console.WriteLine(m.Groups[0]);
}
Console.ReadLine();
}