如何确定字符串是否为数组? [英] How do I determine if a String is an Array?

查看:189
本文介绍了如何确定字符串是否为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个像 ['chad',123,['tankie'],'!!!'] 这样的字符串,我需要返回一个布尔值,说明是否此字符串是否为有效数组。

Given a string like "['chad', 123, ['tankie'], '!!!']", I need to return a boolean stating whether this string is a valid array or not.

对大多数解决方案(包括正则表达式)开放。

Am open to most solutions, including regex.

推荐答案

假设如果要支持Javascript语法的某些子集,可以使用正则表达式删除空格和标量文字,然后检查其余内容是否与嵌套模式 [,[,,,] ,,]相匹配

Assuming you want to support some subset of the Javascript grammar, you can use regular expressions to remove whitespace and scalar literals and then check if what is remaining matches the nested pattern [,[,,,],,,].

let remove = [
    /\s+/g,
    /'(\\.|[^'])*'/g,
    /"(\\.|[^"])*"/g,
    /\d+/g,
];

let emptyArray = /\[,*\]/g;

function stringIsArray(str) {

    for (let r of remove)
        str = str.replace(r, '');

    if (str[0] !== '[')
        return false;

    while (str.match(emptyArray))
        str = str.replace(emptyArray, '');

    return str.length === 0;
}

console.log(stringIsArray("'abc'"));
console.log(stringIsArray(`['abc', ['def', [123, 456], 'ghi',,],,]`));
console.log(stringIsArray(String.raw`
          ['a"b"c', ["d'e'f", 
     [123, [[   [[["[[[5]]]"]]]]], 456], '\"\'""""',,],,]
`));

如果您想支持所有 Javascript语法(例如包含包含数组等对象的数组),则需要一个真正的解析器。我编写了一个名为 litr 的模块,该模块正是这样做的-计算javascript文字,所有这些:

If you want all Javascript grammar to be supported (e.g. arrays that contain objects that contain arrays etc), you need a real parser. I wrote a module called litr that does exactly that - evaluate javascript literals, all of them:

const litr = require('litr'); // or <script src=litr.js>

myJsObject = litr.parse(myString);
console.log('is Array?', Array.isArray(myJsObject))

基本上,它是 PEG.js javascript语法的一个薄包装。

Basically, it's a thin wrapper around a PEG.js javascript grammar.

这篇关于如何确定字符串是否为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆