Extracting a string and removing Whitespace

Viewed 25

I want to extract the string between GROSS and kg and remove whitespace in this text :

ID.NO.  123456
DATE    02/05/21
TIME    01:52 AM
GROSS-   13.5 kg
TARE      0.0 kg
NET  -   13.5 kg

my best result yet is (?<=GROSS)(.*)(?=kg) with the result is - 13.5

still need to remove the whitespace.

2 Answers

You can use 2 capture groups and match the whitespace in between.

Then you can concatenate group 1 and group 2 to get -13.5

\bGROSS(\S*)\s+(\d+(?:\.\d+)?)\s+kg\b

Explanation

  • \bGROSS A word boundary and match GROSS
  • (\S*) Capture group 1, optionally match 0 or more following non whitespace chars
  • \s+ Match 1 or more whitespace chars
  • (\d+(?:\.\d+)?) Capture group 2, match 1 or more digits with an optional decimal part
  • \s+kg\b Match 1 or more whitespace chars, kg and a word boundary

Regex demo

Use

(?<=GROSS\D*)(\d.*?)(?=\s*kg)

See proof

Or, use

GROSS\D*\K\d.*?(?=\s*kg)

See another proof.

Explanation

NODE EXPLANATION
GROSS 'GROSS'
\D* non-digits (all but 0-9) (0 or more times (matching the most amount possible))
\d digits (0-9)
.*? any character except \n (0 or more times (matching the least amount possible))
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times (matching the most amount possible))
kg 'kg'
Related