提问人:Andrus 提问时间:5/19/2023 最后编辑:Andrus 更新时间:5/19/2023 访问量:61
如何将下划线视为空格提取文档编号
How to treat underscore as white space extracting document number
问:
发票字词有时用下划线字符 (_) 分隔,而不是空格:
...
Some nr_11687767_ other 101308591
Invoice Nr.
M230714_some text
Kirjeldus
...
有时它以换行符终止
...
This nr_11687767_KMKR_EE101308591
Invoice Nr.
M230714
01.05.2023
Item
...
或通过其他空格分隔符:
...
Some nr_11687767_ Text
Invoice Nr M230714 Date 01.05.2023
Desc
...
尝试使用正则表达式提取数字
Regex.Match(tekst, @"(?si).*_?Invoice[\s_]?NR[\s_:\.]?(?<arvenumber>.*?)[\s_]");
成功为 true,但 arvenumber 组为空。
如何在 arvenumber 组中只获得数字 M230714?
使用 C# ASP.NET 7
答:
1赞
Dmitry Bychenko
5/19/2023
#1
我建议这样的模式
(?i)Invoice\s+Nr\.?[\s_]+(?<arvenumber>[\p{L}0-9]+)
哪里
(?i) - Ignore case when matching
Invoice - "Invoice"
\s+ - One or more whitespaces
Nr\.? - "Nr" with optional .
[\s_]+ - One or more namespaces or _
(?<arvenumber>[\p{L}0-9]+) - arvenumber which contains of letters and / or digits
评论
0赞
Andrus
5/19/2023
我尝试了修改后的模式,但 arvenumber 组为空。我更新了问题。
0赞
Dmitry Bychenko
5/19/2023
@Andrus:我明白了;让我们尝试一种模式,而不是一个想法
1赞
The fourth bird
5/19/2023
#2
您可以省略使用,因为这将使点也与换行符匹配,这可能会导致匹配过多。(?s)
然后从字符类中取出点,并且仅将其设置为可选,例如,后跟字符类中的 1 个字符。\.?[\s_:.]
(?i).*Invoice[\s_]?NR\.?[\s_:.](?<arvenumber>.*?)[\s_]
或者更具体一点:
(?i)^Invoice[\p{Zs}\t]+Nr\.?\s*(?<arvenumber>[^\W_]+)[\s_]
解释
(?i)
不区分大小写的内联修饰符^
字符串的开头Invoice[\p{Zs}\t]+Nr\.?
匹配后跟 1+ 个不带换行符的空格,然后是可选的Invoice
Nr
.
\s*
匹配可选的 WhiteSpce 字符,也可以匹配换行符(?<arvenumber>[^\W_]+)
组 arvenumber 匹配 1+ 字字符,不带_
[\s_]
匹配空格字符,或者如果这是必需的_
评论
[\s_]
- 空格或_
^Reg nr.*\r?\nInvoice(?: Nr\.)?\s*(?<arvenumber>(?<number>[^\W_]+)(?:_|\s+)[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4})\b
^Invoice Nr\.?\s*(?<arvenumber>[^\W_]+)[\s_]