我已经查看了其他答案,但似乎无法将它们与我的代码相匹配。我的字符串包含如下内容:
"x": {"field": "Horsepower","type": "quantitative"},
"y": {"field": "Miles_per_Gallon","type": "quantitative"}我希望能够替换它,这样它看起来就像:
"x": {"field": "...","type": "quantitative"},
"y": {"field": "...","type": "quantitative"},所以我使用的是str.replace(/regex here/, '...')
我想找出"field": "和",之间的关系。我也可以通过查找以"field": "开头、以",结尾的字符串,然后使用
str.replace(/regex here/, '"field": "...",')
我应该为正则表达式设置什么?此外,在regex背后的解释将不胜感激。
谢谢。
发布于 2017-09-02 00:58:39
正则表达式是用于此工作的错误的工具。字符串看起来是JSON,所以解析它,修改解析后的数据结构,然后重新编码为JSON。
var str = '{ "x": {"field": "Horsepower","type": "quantitative"}, "y": {"field": "Miles_per_Gallon","type": "quantitative"}}';
var data = JSON.parse(str);
data.x.field = '...';
data.y.field = '...';
str = JSON.stringify(data);
document.write(str);
发布于 2017-09-02 00:54:31
使用此模式(\{"[^"]+":\s*")[^"]*并替换为\1... Demo
( # Capturing Group (1)
\{ # "{"
" # """
[^"] # Character not in ["] Character Class
+ # (one or more)(greedy)
": # "":"
\s # <whitespace character>
* # (zero or more)(greedy)
" # """
) # End of Capturing Group (1)
[^"] # Character not in ["] Character Class
* # (zero or more)(greedy)编辑:如果必须存在 'field',请改用 (\{"field":\s*")[^"]* 。
https://stackoverflow.com/questions/46004781
复制相似问题