gpt4 book ai didi

javascript - 在字符串中搜索第一个括号

转载 作者:行者123 更新时间:2023-12-04 08:08:00 25 4
gpt4 key购买 nike

我有不同类型的字符串,如下所示:

  • 苹果数量(1)(1234)
  • 梨的数量(2)(2345)
  • (2)香蕉数量(2344)
  • 橙子数量(绿色)(3455)

  • 我想检查括号之间的值是否为数字。但仅适用于出现在末尾 4 位数字之前的那些。所以不会检查字符串开头的第三个整数。我正在使用 Javascript 并试图使用 string.search()。我正在考虑搜索“)(”。我试着做 string.search("[)(]
    ") 但它没有给我正确的位置或正确搜索它。有没有人对如何搜索 )( 或其他获得该值的方法有任何建议?

    最佳答案

    您可以使用 RegExp以此目的。只需使用 RegExp.prototype.test() 检查给定字符串是否与预期模式匹配(出现在字符串末尾括号中的四位数字之前的数字):

    const stringsArray = ["Amount of Apples(1)(1234)","Amount of Pears(2)(2345)","(2)Amount of Bananas(2344)","Amount of Oranges(Green)(3455)"];

    const pattern = /\(\d+?\)(?=\(\d{4}\)$)/; // for further explanation of this, see https://regex101.com/r/PfBnzk/1/

    for (string of stringsArray) { // loop over every string in the array
    const matchResult = pattern.test(string); // get a boolean TRUE or FALSE of whether or not the string matches the pattern
    console.log(string + " " + matchResult); // print the result of the match to the console
    }


    有关我使用的模式的更通俗的解释,您可以查看 this Regex101 .

    关于javascript - 在字符串中搜索第一个括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66127541/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com