Regex for getting phrases enclosed in Double Quotes

I need help creating a regex. I am programming software that searches for specific words in a string. But I need to also search for phrases . This string is entered by the user in the text field.

I am currently using the following regular expression \s+ to replace spaces with ampersands: word1 word2 word3 to word1&word2&word3

My new requirement should include quotation marks, such as searching for phrases on 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 am open to any idea.

+4
source share
1 answer

This suggests that quests are well balanced - you have an even number of quests, not quests in the middle of words.

You can match for /"([^"]+)"|(\S+)/ - this will result in your words being quoted strings or non-spaces. He fixed the word in group 1 or 2 and you can join get results with delimiter & .

Another option: you can get it in a single replacement, thanks to which it is very similar to the first template, skipping your tokens. Here is a javascript example:

 s = s.replace(/(?:"([^"]+)"|(\S+))\s*/g, '$1$2&'); 

(note that you will have an extra ampersand at the end of the line)

+5
source

Source: https://habr.com/ru/post/1410944/


All Articles