Ajay Suwalka
Ajay Suwalka

Reputation: 531

How to match the content with regex

I have regex as it\(((.|\n)+?)\[8032\]

and the content as

it(`some text
   some text - [208]`, async () => {
    expect(0).toBe(2);
});



it('some text ' +
    'some text - [8032]', async () => {
    expect(1).toBe(0);
});

Now if I execute the regex

I just want

it('some text ' +
    'some text - [8032]

but unfortunately, I am getting a larger match as

it(`some text
   some text - [208]`, async () => {
    expect(0).toBe(2);
});

it('some text ' +
    'some text - [8032]

Upvotes: 0

Views: 49

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You need to have a negative look ahead (?!it) with (.|\n)+? so it rejects the larger match which contains it text and hence you need to use this regex,

it\((((?!it\(')(.|\n))+?)\[8032\]

Here in your own regex, the only addition I have done is this (?!it) which makes sure, the selected string does not contain it within it.

Demo

Upvotes: 0

Robo Mop
Robo Mop

Reputation: 3553

You can try:

it\([^\[]+?\[8032\]['\"]

As shown here: https://regex101.com/r/G95JCw/1/

Explanation -

[^\[]+ tells the regex to match all characters except '[' until it reaches the desired [8032] - which solves your issue about the previous text also being selected.
['\"] at the end is just to select the last quotation marks before async. This part is not needed, but it makes the extraction a bit easier for you :)

Upvotes: 1

Related Questions