gpt4 book ai didi

javascript - JS 正则表达式限制

转载 作者:行者123 更新时间:2023-11-28 00:22:27 25 4
gpt4 key购买 nike

很简单的东西,但还是找不到。。如何限制正则表达式结果?

示例字符串:

io=G4-WfdxQHfBLrcB7AAAC; connect.sid=s%3AKdRP6Bh_bFsN_9Br4TfTykVSqenUgpDA.ighSSEVvoIInT%2Fc7z%2B2HaQQRzwS6p7gkEqJs2ZQbw1k; sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo

我当前的正则表达式:

/\ssid=(.*)/

当前结果是:

sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo

期望的结果是:

s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo

我该如何改进?

最佳答案

您可以使用第一个捕获组作为

match = str.match(/\ssid=(.*)/);
// match[0] will contain match after the `=`

或者更简单地说,你可以写

match = str.match(/\ssid=(.*)/)[1];

示例

str = "io=G4-WfdxQHfBLrcB7AAAC; connect.sid=s%3AKdRP6Bh_bFsN_9Br4TfTykVSqenUgpDA.ighSSEVvoIInT%2Fc7z%2B2HaQQRzwS6p7gkEqJs2ZQbw1k; sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo"  
match = str.match(/\ssid=(.*)/)[1];
// Output
// => s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo

来自MDN

(x)

Matches x and remembers the match. These are called capturing parentheses.

For example, /(foo)/ matches and remembers "foo" in "foo bar". The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

关于javascript - JS 正则表达式限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29861590/

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