I have this string within JavaScript I need to do a match on :
"family name 1" [family name 2] "," firstname middlename
This would make an array with :
["family name 1", "[family name 2]", ",", "firstname", "middlename"]
So basically word(s) that are wrapped in double quotes or brackets will be split as phrases and words that are not within quotes or brackets will be treated as single words or single characters.
I have this regex
currently :
.match(/(?:[^\s"]+|"[^"]*")+/g);
It seems to work well with double quote words but doesn't work with brackets.
please try the below.
(?:[^\s"]+|"[^"]*")+
it is working for
"family name 1", "[family name 2]", ",", "firstname", "middlename"
you can try it in regexpal.com
please let us know if this is your requirement, if this is not, please update the question with the string that needs to be matched.
> re = /(?:"([^"]*)")|(?:\[([^\[\]]*)\])|(\S+)/g;
> s.match(re)
This gives you
[""family name 1"", "[family name 2]", "","", "firstname", "middlename"]
Note that there's no way to strip quotes and brackets with match
, you got to use replace
for that:
result=[]
s.replace(re, function() { result.push(arguments[1]||arguments[2]||arguments[3]) })
Try this:
(?:\[[^\]]+\]|[^\s"]+|"[^"]*")+
I just added the extra check for bracketed phrases:
\[[^\]]+\]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.