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

Regex – get list comma separated allow spaces before / after the comma

I try to extract an images array/list from a commit message:

String commitMsg = "#build #images = image-a, image-b,image_c, imaged , image-e #setup=my-setup fixing issue with px"

I want to get a list that contains:

["image-a", "image-b", "image_c", "imaged", "image-e"]

NOTES:

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

A) should allow a single space before/after the comma (,)

B) ensure that #images = exists but exclude it from the group

C) I also searching for other parameters like #build and #setup so I need to ignore them when looking for #images

What I have until now is:

/(?i)#images\s?=\s?<HERE IS THE MISSING LOGIC>/

I use find() method:

def matcher = commitMsg =~ /(?i)#images\s?=\s?([^,]+)/ 

if(matcher.find()){
    println(matcher[0][1])
}

>Solution :

You can use

(?i)(?:\G(?!^)\s?,\s?|#images\s?=\s?)(\w+(?:-\w+)*)

See the regex demo. Details:

  • (?i) – case insensitive mode on
  • (?:\G(?!^)\s?,\s?|#images\s?=\s?) – either the end of the previous regex match and a comma enclosed with single optional whitespaces on both ends, or #images string and a = char enclosed with single optional whitespaces on both ends
  • (\w+(?:-\w+)*) – Group 1: one or more word chars followed with zero or more repetitions of - and one or more word chars.

See a Groovy demo:

String commitMsg = "#build #images = image-a, image-b,image_c, imaged , image-e #setup=my-setup fixing issue with px"
def re = /(?i)(?:\G(?!^)\s?,\s?|#images\s?=\s?)(\w+(?:-\w+)*)/
def res = (commitMsg =~ re).collect { it[1] }
print(res)

Output:

[image-a, image-b, image_c, imaged, image-e]

An alternative Groovy code:

String commitMsg = "#build #images = image-a, image-b,image_c, imaged , image-e #setup=my-setup fixing issue with px"
def re = /(?i)(?:\G(?!^)\s?,\s?|#images\s?=\s?)(\w+(?:-\w+)*)/
def matcher = (commitMsg =~ re).collect()
for(m in matcher) {
    println(m[1])
}
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