Home > database >  RegEx: Negative lookahead with capture group
RegEx: Negative lookahead with capture group

Time:10-30

I am trying to create a regular expression that will capture JavaScript object properties, but I only want top level properties.
So for example I want to capture this.nodeName but I do not want to capture this.nodeName.length

I am trying the following expression: (this\.\w )(?!\.)
But the lookahead seems to be only working on the \w and not on the whole capture group and I don't understand why this is.
For example if I apply this(?!\.) to this. then it doesn't match thi, so I don't understand why capture groups seem to act differently.

Here is a demo of my expression

Perhaps someone more experienced in regular expression could help me out.

Thanks

CodePudding user response:

Try the following regex expression:

const captured = 'this.party.invitation'.match(/(?<captured>this\.\w*?)(\.|\n|$)/).groups.captured
console.log(captured)

?<captured> gives a name to the group (...). We use a group to capture our desired match. The regex expression also checks at the end if it ends in a dot, a new line (\n) or if it's the end of the line.

CodePudding user response:

You need to check the negative lookahead part first and then capture the following text if pattern is right. Change your regex to this,

(?!this\.\w \.)(this\.\w )

Demo

  • Related