gpt4 book ai didi

c# - RegEx提取前6到10位数字,不包括8位数字

转载 作者:太空狗 更新时间:2023-10-29 20:21:15 24 4
gpt4 key购买 nike

我有以下测试文件名:

abc001_20111104_summary_123.txt
abc008_200700953_timeline.txt
abc008_20080402_summary200201573unitf.txt
123456.txt
100101-100102 test.txt
abc008_20110902_summary200110254.txt
abcd 200601141 summary.txt
abc008_summary_200502169_xyz.txt

我需要从每个文件名中提取一个数字

号码必须是6、7、9 或 10 位数字(因此,不包括 8 位数字)。

如果找到多个,我想得到第一个数字,如果没有找到,我想得到空字符串。

我设法在两步过程中做到这一点,首先删除 8 位数字,然后从我的列表中提取 6 到 10 位数字。

step 1 
regex: ([^0-9])([0-9]{8})([^0-9])
replacement: \1\3

step 2
regex: (.*?)([1-9]([0-9]{5,6}|[0-9]{8,9}))([^0-9].*)
replacement: \2

经过这 2 个步骤后我得到的数字正是我要找的:

[]
[200700953]
[200201573]
[123456]
[100101]
[200110254]
[200601141]
[200502169]

现在,问题是:有没有一种方法可以一步完成?

我见过 this nice solution 类似的问题,但是,如果找到多个,它会给我最新的数字。

注意:使用 The Regex Coach 进行测试。

最佳答案

假设您的正则表达式引擎支持后向断言:

(?<!\d)\d{6}(?:\d?|\d{3,4})(?!\d)

解释:

(?<!\d)   # Assert that the previous character (if any) isn't a digit
\d{6} # Match 6 digits
(?: # Either match
\d? # 0 or 1 digits
| # or
\d{3,4} # 3 or 4 digits
) # End of alternation
(?!\d) # Assert that the next character (if any) isn't a digit

关于c# - RegEx提取前6到10位数字,不包括8位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11722625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com