Home > front end >  Regular expression to match pattern and text afterwards until that pattern occurs again, then repeat
Regular expression to match pattern and text afterwards until that pattern occurs again, then repeat

Time:05-14

I'm trying to write a regex for my Kotlin/JVM program that satisfies:
Given this line of text {#FF00FF}test1{#112233}{placeholder} test2
It should match:
Match 1: #FF00FF as group 1 and test1 as group 2
Match 2: #112233 as group 1 and {placeholder} test2 as group 2

#FF00FF can be any valid 6 character hex color code.

The thing I'm struggling with is to match the text after the color pattern until another color pattern comes up.
Current regex I came up with is \{(#[a-zA-Z0-9]{6})\}((?!\{#[a-zA-Z0-9]{6}\}).*)

CodePudding user response:

You can use

\{(#[a-zA-Z0-9]{6})\}(.*?)(?=\{#[a-zA-Z0-9]{6}\}|$)

See the regex demo. Details:

  • \{ - a { char
  • (#[a-zA-Z0-9]{6}) - Group 1: a # char and six alphanumerics
  • \} - a } char
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible
  • (?=\{#[a-zA-Z0-9]{6}\}|$) - a position immediately followed with a {, #, six alphanumerics and a } char, or end of string.
  • Related