【问题标题】:How to determine multiple substrings of varying size from an API string in javascript如何从javascript中的API字符串中确定多个不同大小的子字符串
【发布时间】:2019-02-15 05:39:36
【问题描述】:

我有一个 API 调用,它作为对象的一部分返回如下内容:

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

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

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

【问题讨论】:

  • 您可以尝试 jsonfy 字符串...然后遍历生成的 JSON
  • 为什么不能使用indexOf()?该值将根据字符串中字符的索引而改变。所以"1.50U".indexOf("U") === 4"100.99U".indexOf("U") === 6...要获得价值,您只需执行aaps.substring(0, aaps.indexOf("U"))
  • indexOf 仍然可以工作。更清洁的方法是使用正则表达式
  • 拆分字符串,如果格式相同,您可以获取删除最后一个字母的数字,例如:string.split()[1].split('U')[0] 和 string .split()[3].split('g')[0].
  • 对不起,我忘了澄清,我想要第二个“U”之前的数字。所以“0.36”数字。 indexof 不起作用,因为它会返回第一个“U”之前的数字,不是吗?

标签: javascript string substring indexof


【解决方案1】:

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"

【讨论】:

  • 我想你是对的,但如果 OP 不熟悉正则表达式,那就是个谜。我见过的最好的正则表达式答案分解并解释了正则表达式的各个部分。
猜你喜欢
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多