简体   繁体   English

用javascript提取字符串的特定部分

[英]extracting specific part of string with javascript

First of all, I know lots of questions like this have been asked before, but it is hard for me to wrap my head around regex so please try to explain it if you can. 首先,我知道很多像这样的问题之前已经被问过了,但是我很难将我的头脑包裹在正则表达式中,所以如果可以的话请尽量解释一下。

I have a string that changes constantly, it is: TOKEN (SwapToken) - 1005.00000127 TOKEN 我有一个不断变化的字符串,它是: TOKEN (SwapToken) - 1005.00000127 TOKEN

Only the number changes, it could vary as little as to 1005.00000128 or to 1500.001 , and I have created a program to extract the string when I require. 只有数字更改,它可能会变化到1005.000001281500.001 ,我已经创建了一个程序,以便在需要时提取字符串。 The only things is, I need to isolate/extract only the number, or maybe extract the string and then create another variable containing just the number. 唯一的事情是,我需要隔离/提取数字,或者可能提取字符串,然后创建另一个只包含数字的变量。

Would the coding look different because the number is subject to change? 编码看起来会有所不同,因为这个数字会有变化吗? How I could accomplish extracting only the number? 我怎么能完成只提取数字? Is Regex the best option, I know there might be a few others. Regex是最好的选择,我知道可能还有其他几个。

Thank you 谢谢

Here's a simple regex you can use 这是一个你可以使用的简单正则表达式

/\\d+\\.\\d+/g

Although it makes assumptions about your input. 虽然它会对您的输入做出假设。 Mainly that nothing else in it will look like a decimal number. 主要是它没有其他内容看起来像一个十进制数字。

\\d means any digit (0 - 9) \\ d表示任何数字(0 - 9)
\\. \\。 means a literal period (.) 表示文字句点(。)
+ means one or more of the preceding characters +表示前面一个或多个字符

You need the backslash because in regex a . 你需要反斜杠,因为在正则表达式中。 means match any character, so you have to escape it. 意味着匹配任何角色,所以你必须逃脱它。

This particular regex finds anything that looks like a decimal number by finding anything that looks like one or more digits followed by a "." 这个特殊的正则表达式通过查找看起来像一个或多个数字后跟“。”的任何内容来查找看起来像十进制数的任何内容。 followed by one or more digits. 后跟一个或多个数字。

 let str = "TOKEN (SwapToken) - 1005.00000127 TOKEN" let num = str.match(/\\d+\\.\\d+/g)[0]; console.log(parseFloat(num)) 

Here's a site where you can test regular expressions out. 这是一个可以测试正则表达式的站点。 It's got some neat features. 它有一些简洁的功能。 And explains what your regex is doing on the right side 并解释你的正则表达式在正确的方面做了什么

https://regex101.com/r/8RuY3A/1 https://regex101.com/r/8RuY3A/1

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

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