简体   繁体   中英

How to parse JSON-like file with regex


I have this structure of my input data, it is just like JSON but not containing strings. I only need to parse few information from these data

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

the code looks like this, what happens here is that it matches but search until last appearance of semicolon. I tried all non-greedy tips and tricks that I have found, but I feel helpless.

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

How can I access value saved under .appVersion variable, please?

You need to escape the . before appVersion since it is a special character in Regex and you can use \\d instead of .* to match only digits. If you want just the number to be captured, without the quotes you can take them out of the parentheses.

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];

If that's what you need...

I'm not sure where the format you're trying to parse comes from, but consider asking (making) your data provider return json string, so you could easily invoke JSON.parse() which works in both node and browser environments.

You can try the following:

 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); 

Your regex is looking for . which is "any character" in a regex. Escape it with a backslash:

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

Don't use .* to capture the value, It's greedy.

You can use something like \\"[^\\"]* - Match a quote, then Any character except quote, as many time as possible.

try

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

Note that the first dot is should also be quoted, and the spaces should be exactly as in your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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