简体   繁体   English

正则表达式获取双引号中的短语

[英]Regex for get phrases enclosed in Double Quotes

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 目前我使用以下正则表达式\\s+用&符替换空格: word1 word2 word3 to word1&word2&word3

My new requirement must include phrases enclosed in quotes, like the searching for phrases in Google. 我的新要求必须包含用引号括起来的短语,例如在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 then join the results with the & delimiter. 您可以匹配/"([^"]+)"|(\\S+)/ - 这将导致您的单词 - 引用字符串或非空格。它捕获组1 2中的单词,然后您可以join &分隔符的结果。

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: 这是一个JavaScript示例:

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

(note that you will have an extra ampersand in the end of the string) (请注意,在字符串的末尾你会有一个额外的&符号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM