简体   繁体   English

使用Javascript正则表达式从字符串的末尾删除int和float

[英]Removing int and float from the end of a string using Javascript regex

I found an answer in this question that is almost perfect but I need a slight tweak. 我在这个问题中找到了一个几乎完美的答案,但我需要稍微调整一下。 I've read the basics of regex and I'm using https://regex101.com/ but I can't figure it out. 我已经阅读了正则表达式的基础知识,我正在使用https://regex101.com/,但我无法理解。

Using "string".replace(/\\d+$/, '') I can remove any numbers from the end of the string. 使用"string".replace(/\\d+$/, '')我可以删除字符串末尾的任何数字。 However I also need to remove any numbers that have a format with a decimal like #.# or ##.# as well as whole numbers, but only when they appear at the end of the string. 但是我还需要删除任何具有小数格式的数字,如#.###.#以及整数,但只有当它们出现在字符串的末尾时才需要。 From regex101 I have found that the $ is for the end of the string. 从regex101我发现$是字符串的结尾。

I can use .replace(/\\d+([.]\\d+)?/g) to remove numbers and floats but it removes them from the entire string, not just when they appear at the end, and I can't work out where to put the $ as I don't really understand regex yet and can't get it to work. 我可以使用.replace(/\\d+([.]\\d+)?/g)删除数字和浮点数,但它会将它们从整个字符串中删除,而不仅仅是当它们出现在最后时,我无法解决在哪里放$因为我还没有真正理解正则表达式而无法让它工作。

It seems such a small and stupid problem but I'd appreciate the help. 这似乎是一个小而愚蠢的问题,但我很感激帮助。

Thanks 谢谢

You may use 你可以用

.replace(/\d+(?:\.\d+)?$/, '')

The pattern matches 模式匹配

  • \\d+ - one or more digits \\d+ - 一个或多个数字
  • (?:\\.\\d+)? - a non-capturing group (the ?: makes it non-capturing, that is, you cannot access the value captured by this group) that matches an optional sequence of a . - 非捕获组?:使其不捕获,即,您无法访问此组捕获的值)与a的可选序列匹配. and then 1+ digits 然后是1+位数
  • $ - end of string. $ - 结束字符串。

To also remove any 0+ whitespaces before the number, add \\s* (where \\s matches any whitespace and * quantifier makes the regex engine match (consecutively) 0 or more of the characters matched with this pattern) at the pattern start. 要在数字之前删除任何0+空格,请在模式开始时添加\\s* (其中\\s匹配任何空格和*量词使正则表达式引擎匹配(连续)0个或更多与此模式匹配的字符)。

See the regex demo . 请参阅正则表达式演示

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

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