简体   繁体   中英

Extract numbers from line not starting with comment symbol using regex

I'm try to replace all numbers not in the comment section. Here is a sample of the file to fix:

/* 2018-01-01 06:00:55 : realtime(0.002) --status(10)-- ++numretLines(0)++  --IP(192.168.1.5) PORT(22)-- queryNo(2)  comment[TO: Too much time]  TYPE[QUERY 4.2]  */
select count(*) from table where id1 = 41111 and id2 = 221144
GO

Basically, I would like to replace numbers in strings not beginning with "/*" .

I came up with the following regex: /^(?!\\/\\*)(?:.+\\K(\\d+?))/gmU

But I only manage to extract the first number of each line not starting with "/*" . How could I extend this to get all the numbers of those rows?

Thanks!

Assuming your regex engine (which you haven't told) supports look behind and look ahead , you can use this regex:

(?<!^\/\*.*)(?:(?<=\s)\d+(?=\s))+

The regex starts by using a negative look behind , looking for the start of line , followed by a slash and a star .

Then it creates a new negative look behind for a White Space , then any number of digits , followed by a negative look ahead for a White Space . This Group is repeated any number of times .

You need to set the global and 'multiline' flag.

The regex skips numbers not surrounded by White Space (for instance 'id1' )

Based on Wiktor Stribiżew comment, I used \\/\\*.*?\\*\\/(*SKIP)(*F)|-?\\b\\d+(\\.\\d+)? to extract the numbers, including decimals and negative values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM