Home > database >  Is it possible to seperate matches with regex, without defining a set length?
Is it possible to seperate matches with regex, without defining a set length?

Time:02-14

So I've come across an issue while using RegEx. As typical, my code is often an absolute mess, and I realized I could probably clean it up with RegEx. So I was making a Minecraft color formatter for a stupid project of mine, which is a completely custom server software that is based on TypeScript. But when I started to make it, I soon figured out that the way I did it doesn't work and only returns one match. Here's an example of what I get:

String: &#ff5c5chello there! this is just a &#aa5cfftest!
Matches: [ "&#ff5c5chello there! this is just a &#aa5cfftest!" ]

And what I expect is:

String: &#ff5c5chello there! this is just a &#aa5cfftest!
Matches: [ "&#ff5c5chello there! this is just a", "&#aa5cfftest!" ]

If it isn't clear, what I want to separate off is &#(hex code), as an example: &#ffffff

The regex I used is /(&#[0-9a-f]{6}.*)*/g

Does anyone know how to do this? Or is this even possible with RegEx?

Edit: Another thing that I must mention is that the start must be another separate match, example:

String: I am the &#5cff5cComputer &#4cee4cMan
Matches: [ "I am the ", "&#5cff5cComputer ", "&#4cee4cMan" ]

CodePudding user response:

I believe this is what you want:

. ?(?=(?:&#|$))

You can play with it and have an explanation of how it works in the following link: https://regex101.com/r/vBUSi9/1

  • Related