Hi guys does anyone know how to write a regex that can look for tokens inside an json string?

{"testt":"{ccc}"}

Currently Im using

text.match(/\{([^\}]+)\}/gm)

I need to get just {ccc} not {"testt":"{ccc}

有帮助吗?

解决方案

IT seems like the tokens you want to find are in properties in quotes. It would be best to JSON.parse first and then look at properties and see if they match the expression, but you can search the raw JSON with something like:

text.match(/"\{([^\}]+)\}"/gm)

This assumes that the tokens start with "{ and end with }". You may also want to try:

text.match(/"\s*\{\s*([^\}]+)\s*\}\s*"/gm)

其他提示

Depending on where the tokens are you could approach it in different ways. If your token's are always in quotations you could include those. The problem really comes down to it being super tricky with JSON because of the way the JSON format operates. If it's always on the value section of the json you might be able to get away with.

(?::)"?\{([^\}]+)\}

However, more than likely you'll need a better white list of tags your are explicitly looking for, rather than just the curly braces.

I noticed the first answer and posted this anyways. If the tags are outside of quotations they'll encounter the problem of the parser attempting to parse the {tag} as JSON.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top