Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression to match pattern and text afterwards until that pattern occurs again, then repeat

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}\}).*)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading