如何从 javascript 中的 API 字符串中确定多个不同大小的子字符串

How to determine multiple substrings of varying size from an API string in javascript

我有一个 API 调用它作为对象的一部分 returns 像这样:

"aaps":"1.50U\/h 0.36U(0.18|0.18) -1.07 0g"

我想从中提取两个子字符串,但子字符串的大小会有所不同。例如,我希望一个变量是 second"U" 之前的数字的子串。但此值介于 0.00 和 100.99 之间。所以我不能指望使用 indexof().

我还希望另一个变量是 "g" 之前的数字的子字符串。此变量的值介于 0 和 250 之间,因此子字符串的字符数会有所不同。

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
}

正则表达式捕获你需要的两个数字,exec函数将它们提取到一个数组中。正则表达式的含义如下:

.+                         | 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"