我正在尝试获取一个包含编号列表的字符串,该编号列表的旁边是数据项,然后根据每个数字旁边的数据将它们分成多个字符串。我尝试使用正则表达式,但这引起了一些问题,因为某些数据是货币值,例如120,000.00英镑。
示例数据为
Mr Test Test
£100,000.00
5 Test Road, Test Street
测试输入:
string testInput = "1. Mr Test Test 2. £100,000 3. 5 Test Road"
但是,由于使用PdfTextStripper
PDFBox
从 PDF 拉出了字符串,因此编号列表可能会出现在字符串的不同行中
有没有一种方法可以准确地拆分呢?
我本来是使用indexof并依赖于下一个数据项标题作为停止点,但是数据并不总是相同的({15
指向一个,{{1} })。
所需的结果是:
25
任何帮助将不胜感激
答案 0 :(得分:1)
让我们实现一个简单的生成器;我们可以在循环中找到一行一行:
代码:
private static IEnumerable<string> ParseListToLines(string value) {
int start = 0;
bool first = true;
for (int index = 1; ; ++index) {
string toFind = $"{index}.";
int next = value.IndexOf(toFind, start);
if (next < 0) {
yield return value.Substring(start);
break;
}
if (!first) // we don't return text before the 1st item
yield return value.Substring(start, next - start);
first = false;
start = next + toFind.Length;
}
}
演示:
string testInput = "1. Mr Test Test 2. £100,000 3. 5 Test Road";
string[] lines = ParseListToLines(testInput).ToArray();
// string Name = lines[0].Trim();
// string Money = lines[1].Trim();
// string Address = lines[2].Trim();
Console.Write(string.Join(Environment.NewLine, lines));
结果:
Mr Test Test
£100,000
5 Test Road
编辑:带有精心修饰的测试的更多演示(内部和不包含项目的新行;一位和两位数字标记;文本-**
-在初始{{ 1}}标记):
1.
结果:
// Let's build multiline string...
string testInput = "**\r\n" + string.Join(Environment.NewLine, Enumerable
.Range(1, 12)
.Select(i => $"{i,2}.String #{i} {(i < 3 ? "\r\n Next Line" : "")}"));
Console.WriteLine("Initial:");
Console.WriteLine();
Console.WriteLine(testInput);
Console.WriteLine();
Console.WriteLine("Parsed:");
Console.WriteLine();
// ... and parse it into lines
string[] lines = ParseList(testInput)
.Select(line => line.Trim())
.Select((item, index) => $"line number {index} = \"{item}\"")
.ToArray();
Console.WriteLine(string.Join(Environment.NewLine, lines));
编辑2:好吧,让我们尝试另一个测试:
Initial:
** // This text - before initial "1." marker should be ingnored
1.String #1 // 1st item contains multiline text
Next Line // 1st item continuation
2.String #2 // Again, multiline marker
Next Line
3.String #3
4.String #4
5.String #5
6.String #6
7.String #7
8.String #8
9.String #9
10.String #10 // two digit markers: "10.", "11.", "12."
11.String #11
12.String #12
Parsed:
line number 0 = "String #1 // 1st item is multiline one
Next Line"
line number 1 = "String #2 // 2nd item is multiline as well
Next Line"
line number 2 = "String #3"
line number 3 = "String #4"
line number 4 = "String #5"
line number 5 = "String #6"
line number 6 = "String #7"
line number 7 = "String #8"
line number 8 = "String #9"
line number 9 = "String #10"
line number 10 = "String #11"
line number 11 = "String #12"
结果:
string testInput =
"1. test 5. wrong 2. It's Correct 3. OK 4. 1. 2. 3. - all wrong 5. Corect Now;";
string[] report = ParseList(testInput)
.Select(line => line.Trim())
.ToArray();
Console.Write(string.Join((Environment.NewLine, report));