jorgen
jorgen

Reputation: 3593

Regular expression matching simple json within text

I'm failing to write a reg exp that catches things all occurences of { key: something } where something can be anything except } or . I've tried

{ key: [^}]* }
{ key: [^} ]* }
{ key: (.*?)({| ) }
{ key: (.*?)({) }
{ key: (?!.*({| )) }
{ key: (?!.*({)) }

of these the first one works sometimes, not according to any pattern I can see. I'm using these in javascript:

const pattern = '{ key: [^}]* }';
const regExp = new RegExp(pattern, 'igm');
let match = true;

do {
  match = regExp.exec(text);
  if (match) {
     // use result
  }
} while (match);

(I've also tried adding regExp.lastIndex = 0;, and setting regExp = null and redefining, in the loop).

However I don't think it's (only) a javascript problem; They don't work either on the online regexp tester.

I need the character indices; as an example I would like

kjh { key: sfdg } lkk { key: a }

to yield (5, 13) and (23, 10) (might be some off by one errors there)

Any suggestions?

EDIT: If relevant, the usecase is to highlight text following this pattern in an editor, using draft.js

Upvotes: 1

Views: 892

Answers (2)

guest271314
guest271314

Reputation: 1

To match the value of JSON you can convert the object to valid JSON match the property surrounded by double quotes followed by : and any characters followed by closing }.

See also

var o = {key:123};

var json = JSON.stringify(o);

var prop = `"key":`;

var re = new RegExp(`${prop}.+(?=})`);

console.log(json.match(re)[0].split(new RegExp(prop)).pop());

Upvotes: 0

Joseph
Joseph

Reputation: 119847

Don't.

Parse the JSON into an object with JSON.parse, find the key programmatically.

kjh { key: sfdg } lkk { key: a }

This is also not valid JSON. If this is some data from the server, serve it in some correct data transfer format (i.e. XML, YAML, JSON) and not some arbitrary, structureless string.

Upvotes: 2

Related Questions