1

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

jorgen
  • 3,425
  • 4
  • 31
  • 53

2 Answers2

2

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.

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • The usecase is to highlight text in an editor that follows this pattern (with entities from https://draftjs.org/), so it must be able to handle everything - will edit the OP. There still might be some approach similar to what you're saying though, I like it – jorgen Jan 28 '18 at 21:32
  • 1
    @jorgen All the more reason to use a real parser than just plain regular expressions. Your code should be able to tell JSON apart from strings that _look_ like JSON. – Joseph Jan 28 '18 at 21:39
  • Ok. So I'm thinking to find all occurences of `{` and `}`, try `JSON.parse` on what's between (including the brackets) and inspect the results. Sound? – jorgen Jan 28 '18 at 21:41
0

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());
guest271314
  • 1
  • 15
  • 104
  • 177