简体   繁体   English

捕获任意数量的尾随数字

[英]Capturing arbitrary numbers of trailing digits

I have some spreadsheets where people have written 13.14 (for example), where the decimal point is a delimiter not a number - ie it would have been better to write 13,14 or 13-14 .我有一些电子表格,人们写了 13.14 (例如),其中小数点是分隔符而不是数字 - 即最好写13,1413-14 Between Excel and read_excel this can get converted to something like 13.140000000000001 , or 9.1699999999999999 or 13.279999999999999 .在 Excel 和read_excel之间,这可以转换为13.1400000000000019.169999999999999913.279999999999999类的东西。 I need to chop off the 9 s (and annoyingly round the number up) or the 0..01 s I thought a regex like:我需要砍掉9 s(并将数字向上取整)或0..01 s,我认为正则表达式如下:

^(.*)0{3,}[12]$

might work, but all it does is capture three of the trailing 0's and the 1. Similarly可能有效,但它所做的只是捕获三个尾随的 0 和 1。类似地

^(.*)9{3,}$

Does not capture all of the 9s.没有捕捉到所有的 9。 I could probably specify the 0 pattern exactly (13 x 0 + 1), but the 9s are trickier because there might be 13 or 14 of them.我可以准确地指定 0 模式(13 x 0 + 1),但 9 更棘手,因为它们可能有 13 或 14 个。

Regex are not the right tool here.正则表达式在这里不是正确的工具。 You are going to fail at rounding up, and you're currently failing at matching something like "129999".您将无法四舍五入,而您目前无法匹配“129999”之类的内容。 You need to interpret these each as a number, not as a sequence of characters.您需要将它们解释为一个数字,而不是一个字符序列。

The trick turned out being more specific about the numbers that I wanted to keep.事实证明,这个技巧更具体地说明了我想要保留的数字。 I used negative lookahead to make sure I only dealt with "possible" numbers, ie I want 1,2,3,..,10,11 etc. but I don't want 09 for example.我使用负前瞻来确保我只处理“可能的”数字,即我想要 1、2、3、..、10、11 等,但我不想要 09。 The regex for the zeros is零的正则表达式是

^(([1-9](?!0)|[12][0-9])\\.([1-9](?!0)|[12][0-9]))0{3,}[12]$

and

^(([1-9](?!0)|[12][0-9])\\.([1-9](?!0)|[12][0-9]))9{3,}$

Note this is for R, so the .请注意,这是针对 R,所以. is double-escaped, which it wouldn't be in other languages.是双重转义的,在其他语言中不会。

The rounding was handled by capturing the cleaned numbers, incrementing the second number by 1, and concatenating them.通过捕获清理后的数字、将第二个数字增加 1 并将它们连接起来来处理舍入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM