-->

匹配,并使用存储在变量中的字符串的一部分JScript.NET(Matching and stori

2019-10-21 09:10发布

我与一些摆弄一对提琴手脚本 ,它使用JScript.NET。 我有格式的字符串:

{"params":{"key1":"somevalue","key2":"someothervalue","key3":"whatevervalue", ...

我想匹配,并显示"key2":"someothervalue"哪里someothervalue可以是任何值,但关键是静态的。

用好老sedbash ,我可以代替我正在寻找与部分:

$ a='{"params":{"key1":"somevalue","key2":"someothervalue","key3":"whatevervalue", ...'
$ echo $a | sed -r 's/"key2":"[^"]+"/replaced/g'
{"params":{"key1":"somevalue",replaced,"key3":"whatevervalue", ...

现在。 而不是替换它,我想提取部分进入使用JScript.NET的变量。 那怎么可以呢?

Answer 1:

最优雅的方式是使用JSON解析器。 我个人的偏好是使用导入IE的JSON解析器htmlfile COM对象。

import System;

var str:String = '{"params":{"key1":"foo","key2":"bar","key3":"baz"}}',
    htmlfile = new ActiveXObject('htmlfile');

// force htmlfile COM object into IE9 compatibility
htmlfile.IHTMLDocument2_write('<meta http-equiv="x-ua-compatible" content="IE=9" />');

// clone JSON object and methods into familiar syntax
var JSON = htmlfile.parentWindow.JSON,

// deserialize your JSON-formatted string
    obj = JSON.parse(str);

// access JSON values as members of a hierarchical object
Console.WriteLine("params.key2 = " + obj.params.key2);

// beautify the JSON
Console.WriteLine(JSON.stringify(obj, null, '\t'));

编译,链接,并运行在以下控制台输出结果:

params.key2 = bar
{
        "params": {
                "key1": "foo",
                "key2": "bar",
                "key3": "baz"
        }
}

可替换地,也有至少一个耦合.NET命名空间 ,其提供方法对象序列化为JSON字符串,和反序列化JSON字符串为对象。 不能说我是一个球迷,虽然。 的ECMAScript的符号JSON.parse()JSON.stringify()肯定容易得多,深刻比任何neckbeard疯狂是那么陌生,在微软回事 。


虽然我当然不建议刮JSON(或任何其他分层标记,如果它可以帮助)为复杂的文本,JScript.NET会处理很多熟悉的JavaScript方法和对象,包括字符串regex对象和正则表达式替换。

SED语法:

echo $a | sed -r 's/("key2"):"[^"]*"/\1:"replaced"/g'

JScript.NET语法:

print(a.replace(/("key2"):"[^"]*"/, '$1:"replaced"'));

JScript.NET,就像JScript和JavaScript的,也允许要求更换一个lambda函数。

print(
    a.replace(
        /"(key2)":"([^"]*)"/,

        // $0 = full match; $1 = (key2); $2 = ([^"]*)
        function($0, $1, $2):String {
            var replace:String = $2.toUpperCase();
            return '"$1":"' + replace + '"';
        }
    )
);

...或者提取的价值key2使用RegExp对象exec()方法:

var extracted:String = /"key2":"([^"]*)"/.exec(a)[1];
print(extracted);

只是要小心的是,虽然,因为检索元件[1]的结果的exec()将导致折射率外的范围内的异常,如果不存在匹配。 可能要么需要if (/"key2":/.test(a))或添加try...catch 。 或者更好的,只是在做我前面说的和反序列化JSON你到一个对象。



文章来源: Matching and storing part of a string in a variable using JScript.NET