Adam Mrozek
Adam Mrozek

Reputation: 1490

How to extract all numbers not in quotation marks using regex?

I need to extract all numbers in string which are NOT in quotation marks and are NOT the part of variable name.

In Example, I have this code:

const VariableA1 = '5;0;5;5;0;5;3;3;7;7';
const M65 = true;

type MyType = record
    H: array[0..27] of integer;
    S: integer;
end;

function B(sep: Char) : integer;
var i: integer;
begin
    i:= 1;
    return sep[0];
end;

I resolved it myself, here is the code:

(?<![a-zA-Z])[0-9]+(?=([^']*'[^']*')*[^']*$)

but regex101 throwing timeout error - catastrophic backtracking. Evaluation of this pattern is 8 seconds long.

Is there way to this better? Can you help me optimize this pattern?

Upvotes: 2

Views: 71

Answers (2)

vks
vks

Reputation: 67998

\b[0-9]+(?=(?:[^']*'[^']*')*[^']*$)

You can simply use this.See demo.

https://regex101.com/r/gT6vU5/4

For Faster approach you can use

\b[0-9]+(?=(?>(?:[^']*'[^']*')*)[^']*$)

           ^^

Make use of atomic groups.See demo.

https://regex101.com/r/gT6vU5/6

EDIT:

if you are sure that quotes dont span multiple lines you can use

\b[0-9]+(?![^\n]*')

See demo.

https://regex101.com/r/gT6vU5/5

Upvotes: 1

Mayur Koshti
Mayur Koshti

Reputation: 1862

You can also try this:

\*{1,}\d+\*{1,}

Upvotes: 0

Related Questions