Home > Back-end >  Split complex string into mutliple parts using regex
Split complex string into mutliple parts using regex

Time:07-04

I've tried a lot to split this string into something i can work with, however my experience isn't enough to reach the goal. Tried first 3 pages on google, which helped but still didn't give me an idea how to properly do this:

I have a string which looks like this:

My Dogs,213,220#Gallery,635,210#Screenshot,219,530#Good Morning,412,408#

The result should be:

MyDogs
213,229
Gallery
635,210
Screenshot
219,530
Good Morning
412,408

Anyone have an idea how to use regex to split the string like shown above?

CodePudding user response:

Given the shared patterns, it seems you're looking for a regex like the following:

[A-Za-z ] |\d ,\d 

It matches two patterns:

  • [A-Za-z ] : any combination of letters and spaces
  • \d ,\d : any combination of digits a comma any combination of digits

Check the demo here.


If you want a more strict regex, you can include the previous pattern between a lookbehind and a lookahead, so that you're sure that every match is preceeded by either a comma, a # or a start/end of string character.

(?<=^|,|#)([A-Za-z ] |\d ,\d )(?=,|#|$)

Check the demo here.

  • Related