Eych
Eych

Reputation: 323

Remove everything before a regex pattern

I have different data in this format:

ISIN: LU0799639926

I created a regex to filter the important data:

\w{2}\d{10}

The thing is that I want to delete everything that is before and behind my pattern. I have already tried

[^\w{2}\d{10}]* 

It selects everything but my pattern, it just doesn't work. Does anyone have a solution?

Upvotes: 1

Views: 5190

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use a .* subpattern to get anything before and after, capture your substring into a capturing group and then replace with a $1 backreference:

.*(\w{2}\d{10}).*

Replace with $1.

See demo

Perhaps, you will be safer with .*([A-Z]{2}\d{10}).*, as \w may also capture digits, and [A-Z] will only match uppercase letters.

If you have multiple values in the input string, perhaps, you will be more interested in getting a delimited string, e.g.:

.*?([A-Z]{2}\d{10})

To replace with $1;.

See another demo

Upvotes: 2

Maroun
Maroun

Reputation: 95948

Inside the character class

[^\w{2}\d{10}]

{ and } are treated as the literals { and }, they loose their regex meaning.

Try:

.*(\w{2}\d{10})

This will catch the pattern you want, then you can easily replace it with whatever you want.

Upvotes: 0

Related Questions