【发布时间】:2018-06-15 09:09:03
【问题描述】:
我需要使用 JavaScript 分析一个字符串,以确定它是否在其中的任何位置包含一些 JSON。
我有一个适用于 RegEx 101 和 PHP 的模式:
$pattern = '
/
\{ # { character
(?: # non-capturing group
[^{}] # anything that is not a { or }
| # OR
(?R) # recurses the entire pattern
)* # previous group zero or more times
\} # } character
/x
';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
但是,我正在努力将其转换为 JavaScript。这是我目前所拥有的:
var txt = draft.content. // gets a long text string
jsontest = txt.match(/\{(?:[^{}]|(?R))*\}/xg);
但这会得到一个错误提示:
正则表达式中的无效字符 (?
任何人都可以建议修改该正则表达式模式吗?或者有另一种不需要正则表达式的 JavaScript 方法吗?
这是输入:
New test nested braces
{
"employee":{ "name":"John", "age":30, "city":"New York" },
"location":{"street":"100 Main","City":"Houston","Zip":"77001"}
}
And other text that is not part of the string I need
输出应该是json字符串
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: javascript json regex