繁体   English   中英

如何使用正则表达式解析类似JSON的文件

[英]How to parse JSON-like file with regex


我的输入数据具有这种结构,就像JSON一样,但不包含字符串。 我只需要解析这些数据中的一些信息

{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}'''

代码看起来像这样,这里发生的是它匹配但搜索到最后一个分号。 我尝试了所有发现的非贪婪技巧和窍门,但我感到无助。

const regex = /.appVersion = (".*"?);/
const found = data.match(regex)
console.log(found)

请问如何访问保存在.appVersion变量下的值?

您需要逃脱. appVersion之前,因为它是Regex中的特殊字符,您可以使用\\d而不是.*来仅匹配数字。 如果只想捕获数字,而没有引号,则可以将其从括号中删除。

const regex = /\.appVersion = "(\d+)";/
const found = data.match(regex)
const appVersion = found[1];
const string = '{ .appVersion = "1230"; DisplayStrings = (...(continues)';
const appVersion = string.match(/\.appVersion\s*=\s*"([^"]+)"/)[1];

如果那是您所需要的...

我不确定您要解析的格式来自哪里,但是可以考虑让(让)数据提供者返回json字符串,因此您可以轻松地调用可在节点和浏览器环境中使用的JSON.parse()

您可以尝试以下方法:

 var data='{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}'; const regex = /.appVersion = [^;]*/ //regex test: https://regex101.com/r/urX53f/1 const found = data.match(regex); var trim = found.toString().replace(/"/g,''); // remove the "" if necessary console.log(found.toString()); console.log(trim); 

您的正则表达式正在寻找. 这是正则表达式中的“任何字符”。 用反斜杠转义:

/\.appVersion = ("\d+");/

不要使用.*来获取值,这是贪婪的。

您可以使用\\"[^\\"]* -尽可能匹配引号,然后匹配除引号之外的任何字符。

尝试

const regex = \.appVersion = \"([^\"]*)\";

请注意,第一个点也应加引号,并且空格应与示例中的完全相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM