Is there an easier way to find regex of the string?

Viewed 62

I'm just beginning with regex and just got stuck in a difficult situation. The string i have is:

ITEM DESCRIPTION:  KING AUTHUR 2LB FLOUR     PACK: 10                              SIZE: 0011.00 OZ

I need to get the parts within "< >":

ITEM DESCRIPTION:  <KING AUTHUR 2LB FLOUR>     PACK: <10>                              SIZE: <0011.00 OZ>

I've tried

: *([\w\.]+ ?[\w]* [\d\w]* *[\w]*)

which is not 100% accurate and feels repetitive and also becomes tedious when the text gets longer (multiple key:value).

Is there a generalized way of getting all the values from a key:value pair from a text of indefinite length? And also why something like (ITEM).*: doesn't stop at ITEM DESCRIPTION: but selects all the way upto ITEM DESCRIPTION: ... SIZE: if I just want to get the first key?

1 Answers

Here is one way with a PCRE-compatible regex:

:\s*\K.*?(?=\s*\w+:|$)

See the regex demo. An ECMAScript 2018+/.NET/Python PyPi regex compliant pattern is

(?<=:\s*\b).*?(?=\s*\w+:|$)

See this regex demo.

For the rest, you may rely on capturing:

:\s*(.*?)(?=\s*\w+:|$)

See the regex demo.

Details:

  • :\s* - a colon and zero or more whitespaces
  • \K - a match reset operator that discards the whole text matched so far from the match memory buffer
  • (?<=:\s*\b) - a positive lookbehind that matches a location that is immediately preceded with :, zero or more whitespaces and a word boundary
  • .*? - any zero or more chars other than line break chars as few as possible
  • (?=\s*\w+:|$) - a positive lookahead that matches a location in string that is immediately followed with zero or more whitespaces, one or more word chars and then a colon, or end of string.
Related