正则表达式仅捕获数字字段,剥离$和逗号,如果有任何字母数字,则无匹配
我正在尝试写一条正则票据,该正则可以从一个值中剥离出$,并且如果有其他非数字,则根本不匹配。
$100 -> 100
$12,203.00 -> 12203.00
12JAN2022 -> no match
我已经接近了这一点:
^(?:[$,]*)(([0-9.]{1,3})(?:[,.]?))+(?:[$,]*)$
但是,这并不能以$ 1的价格正确捕获数字值,因为重复数字被捕获为像子组捕获一样,您可以在此处看到 https://regex101.com/r/4bojtb/1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用命名的捕获组捕获数字的所有部分,然后将它们连接。虽然,替换不需要作为后处理步骤的所有炭是更直接的。
这是一个示例代码:
请参阅 c#demo 。输出:
正则是
请参见详细信息:
^
- 字符串的开始\ $*
- 零或更多美元符号(?:(? d {1,3})(?:,(?< v> \ d {3}))*|(? “ v”),然后零或更多逗号的逗号,然后出现三个数字(被捕获为“ V”组),或一个或多个数字(被捕获为“ V”组为“ V”)
(?< v> \。 \ d+)?
- 可选出现。
和一个或多个数字(全部捕获到组“ V”)$
- 字符串的结尾。You can use a named capturing group to capture all parts of the number and then concatenate them. Although, it is more straight-forward to replace all chars you do not need as a post-processing step.
Here is an example code:
See the C# demo. Output:
The regex is
See the regex demo. Details:
^
- start of string\$*
- zero or more dollar symbols(?:(?<v>\d{1,3})(?:,(?<v>\d{3}))*|(?<v>\d+))
- either one to three digits (captured into Group "v") and then zero or more occurrences of a comma and then three digits (captured into Group "v"), or one or more digits (captured into Group "v")(?<v>\.\d+)?
- an optional occurrence of.
and one or more digits (all captured into Group "v")$
- end of string.我不知道如何在单一言论中实现这一目标,但是在这里个人意见我发现将问题分为较小的步骤是一个好主意 - 将来更容易实施和维护/理解而不牺牲时间了解魔术。
替换所有
$
和,
到空字符串[\ $ \,]
=&gt; ``仅匹配数字和时期作为捕获组(当然,您可能需要将其与允许的期间位置等相一致)
^((\ d {1,3} \。?)+)$
希望这会有所帮助!
I don't know how to achieve this in single regexp, but personal opinion here I find dividing the problem into smaller steps a good idea - it's easier to implement and maintain/understand in the future without sacrificing time to understand the magic.
replace all
$
and,
to empty string[\$\,]
=> ``match only digits and periods as a capture group (of course you may need to align this with your requirements on allowed period locations etc.)
^((\d{1,3}\.?)+)$
Hope this helps!