gpt4 book ai didi

javascript - 正则表达式将字符串拆分为单独的键

转载 作者:行者123 更新时间:2023-11-30 18:35:18 24 4
gpt4 key购买 nike

我正在做一个有趣的项目,但我在为此编写正则表达式时遇到了一些麻烦。

使用正则表达式和 Javascript,我想将我的输入字符串拆分为一个“键”数组。具有无效键的字符串应返回 0 个键(null、空数组,随便什么都可以)。

“规范”

<input string>      => <matches>

# named keys
a => ['a']
b => ['b']
foo[bar] => ['foo', 'bar']

# numeric keys are ok too
a[0] => ['a', '0']
b[1] => ['b', '1']

# 'push' syntax is also valid
push[] => ['push', '']
hello[] => ['hello', '']

# complex!
complex[named][0][] => ['complex', 'named', '0', '']

无效示例

# named keys must start with [a-zA-Z]
_invalid => null
3foo[abc] => null

# named keys can include a number as long as they start with a letter
foo3valid[this_is_valid_2] => ['foo3valid', 'this_is_valid_2']

到目前为止我有什么

var regex = /^(?:\[?([a-zA-Z][a-zA-Z0-9_]*|[a-zA-Z0-9_]*)\]?)+$/g;
var keys = [];

myInput.replace(regex, function(match,capture,pos,source){
keys.push(capture);
});

console.log(myInput, keys);

它是如何失败的

我的正则表达式只匹配最后一个“键”例如,

# should be ['a', 'b', 'c']
a[b][c] => ['c']

jsFiddle 修补

jsfiddle

最佳答案

我采用了另一种方法来获得预期的结果:

  1. 测试给定的短语是否有效。
  2. 如果有效,使用全局匹配创建一个数组。

代码: fiddle :http://jsfiddle.net/MVJZc/2/

///Example
var myInput = "a[b][][c]";

var validate = /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
pattern = /[a-zA-Z0-9_]+|(?=\[\])/g,
//(?=\[\]) is used to create an empty entry for []
keys = null;
if (validate.test(myInput)) {
keys = myInput.match(pattern);
}

注意:如果你想扩展模式,例如要包含 $ 字符,请修改第一个 RegEx。第二个 RegEx (pattern) 应至少包含所有有效字符。

关于javascript - 正则表达式将字符串拆分为单独的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8404750/

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