I need help to build a regular expression. I’m programming a software that looks for certain words in a string. But I need to also look for phrases. This string is entered by the user in a text box.
Currently I use the following regular expression \s+ to replace spaces by ampersands:
word1 word2 word3 to word1&word2&word3
My new requirement must include phrases enclosed in quotes, like the searching for phrases in Google.
"word1 word2" "word3 word4" word5
Must be:
word1 word2&word3 word4&word5
Thanks in advance.
EDIT: If there is another way or another approach to do the same, I’m open to any idea.
This assumes the quests are well balanced – you have an even number of quests, and not quests in middle of words.
You can match for
/"([^"]+)"|(\S+)/– this will result in your words – quoted strings or non-spaces. It captured the word in group 1 or 2, and you can thenjointhe results with the&delimiter.Another option: you can get it in a single replace, by which is very similar way to the first pattern, by skipping over your tokens. Here’s a JavaScript example:
(note that you will have an extra ampersand in the end of the string)