[英]How to determine multiple substrings of varying size from an API string in javascript
I have an API call that as part of the object returns something like this: 我有一个API调用,作为对象的一部分返回了如下内容:
"aaps":"1.50U\/h 0.36U(0.18|0.18) -1.07 0g"
I would like to pull two substrings out of this but the size of the substrings will vary. 我想从中拉出两个子串,但是子串的大小会有所不同。 For example, I would like one variable to be the substring of the number that precedes the second "U". 例如,我希望一个变量是第二个 “ U”之前的数字的子字符串。 But this value will be anywhere between 0.00 and 100.99. 但是此值将在0.00到100.99之间。 So I can't just count on using indexof()
. 所以我不能只指望使用indexof()
。
As well I would like another variable to be the substring of the number that precedes the "g". 同样,我希望另一个变量是“ g”之前数字的子字符串。 This variable will have a value of anywhere between 0 and 250 so the number of characters of the substring will vary. 此变量的值将介于0到250之间,因此子字符串的字符数将有所不同。
JavaScript's exec
function is great for this. JavaScript的exec
函数对此非常有用。
var string = '1.50U\/h 0.36U(0.18|0.18) -1.07 0g';
var regex = /.+U.+(\d+\.\d{2})U.+(\d+)g/;
var match = regex.exec(string);
if (match) {
console.log('Matches: ' + match[1] + ', ' + match[2]);
// Matches: 0.36, 0
}
The regular expression captures the two numbers you need, and the exec
function extracts them into an array. 正则表达式捕获您需要的两个数字,然后exec
函数将它们提取到数组中。 Here's what the regular expression means: 正则表达式的含义如下:
.+ | Match one or more consecutive characters (any)
U | Match the letter "U"
.+ | Match one or more consecutive characters (any)
( | Capture the following:
\d+ | One or more consecutive digits
\. | The character "."
\d{2} | Exactly 2 consecutive digits
) | End capture
U | Match the letter "U"
.+ | Match one or more consecutive characters (any)
(\d+) | Capture one or more consecutive digits
g | Match the letter "g"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.