Monday, July 6, 2009

Regex to match spaces inside quotes

I had a need to match spaces inside double quotes.  I was splitting a list of tags on spaces, but ran into problems if there were spaces inside quotes.  Take this string for example:

tag1 tag2 tag3 "this makes up tag4" tag5 'this is tag6' tag7

I basically needed this list:
tag1
tag2
tag3
this makes up tag 4
tag5
this is tag 6
tag7


A quick search on stackoverflow.com led me to this regular expression:
m/([^\s"']+|"[^"]*"|'[^']*')/g

Regex for splitting a string using space when not surrounded by single or double quotes - Stack Overflow


No comments:

Post a Comment