为什么在使用某些正则表达式模式时我的函数不能正确替换 [英] Why doesn't my function correctly replace when using some regex pattern

查看:37
本文介绍了为什么在使用某些正则表达式模式时我的函数不能正确替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这个SO 问题

我做了一个函数来看看我是否可以正确格式化任何数字.下面的答案适用于 https://regex101.comhttps://regexr.com/,但不在我的函数内(在节点和浏览器中尝试):常量

I made a function to see if i can correctly format any number. The answers below work on tools like https://regex101.com and https://regexr.com/, but not within my function(tried in node and browser): const

const format = (num, regex) => String(num).replace(regex, '$1')

基本上给定任何整数,它不应超过 15 位有效数字.给定小数点后,不能超过2个小数点.

Basically given any whole number, it should not exceed 15 significant digits. Given any decimal, it should not exceed 2 decimal points.

所以...现在

format(0.12345678901234567890, /^\d{1,13}(\.\d{1,2}|\d{0,2})$/)

返回 0.123456789012345678 而不是 0.123456789012345

returns 0.123456789012345678 instead of 0.123456789012345

但是

format(0.123456789012345,/^-?(\d*\.?\d{0,2}).*/)

按预期返回格式化为 2 个小数点的数字.

returns number formatted to 2 deimal points as expected.

推荐答案

让我试着解释一下发生了什么.

Let me try to explain what's going on.

对于给定的输入 0.12345678901234567890 和正则表达式 /^\d{1,13}(\.\d{1,2}|\d{0,2})$/,让我们一步一步来看看发生了什么.

For the given input 0.12345678901234567890 and the regex /^\d{1,13}(\.\d{1,2}|\d{0,2})$/, let's go step by step and see what's happening.

  1. ^\d{1,13} 确实匹配字符串的开头 0
  2. (\. 现在您打开了一个新组,它确实与 匹配.
  3. \d{1,2} 它确实找到了数字 12
  4. |\d{0,2} 所以这部分跳过
  5. ) 所以这是你的捕获组的结束.
  6. $ 这表示字符串的结尾,但它不会匹配,因为你还有 345678901234567890 剩余.
  1. ^\d{1,13} Does indeed match the start of the string 0
  2. (\. Now you've opened a new group, and it does match .
  3. \d{1,2} It does find the digits 1 and 2
  4. |\d{0,2} So this part is skipped
  5. ) So this is the end of your capture group.
  6. $ This indicates the end of the string, but it won't match, because you've still got 345678901234567890 remaining.

Javascript 返回整个字符串,因为匹配最终失败.

Javascript returns the whole string because the match failed in the end.

我们试着去掉末尾的 $ ,变成 /^\d{1,13}(\.\d{1,2}|\d{0,2})/

Let's try removing $ at the end, to become /^\d{1,13}(\.\d{1,2}|\d{0,2})/

你会得到".12345678901234567890".这会产生几个问题.

You'd get back ".12345678901234567890". This generates a couple of questions.

为什么前面的 0 被删除了?

Why did the preceding 0 get removed?

因为它不是您匹配组的一部分,用 () 括起来.

Because it was not part of your matching group, enclosed with ().

为什么我们没有得到两位小数,即.12?

请记住,您正在执行 replace.这意味着默认情况下,原始字符串将保留在原位,只有匹配的部分才会被替换.由于 345678901234567890 不是匹配的一部分,所以它保持不变.唯一匹配的部分是0.12.

Remember that you're doing a replace. Which means that by default, the original string will be kept in place, only the parts that match will get replaced. Since 345678901234567890 was not part of the match, it was left intact. The only part that matched was 0.12.

这篇关于为什么在使用某些正则表达式模式时我的函数不能正确替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆