
当一个句子中有多对引号的时候,例如:
Last "week" I "went" to the "theatre"
正则表达式"[^"]+"只能匹配最后一个引号里的内容:theatre
我想匹配第二个引号里的内容( went ),该怎么写规则呢?
1 choury 2019-06-20 11:17:35 +08:00 via Android 多匹配点,然后别的不捕获 |
2 mooncakejs 2019-06-20 11:22:21 +08:00 'Last "week" I "went" to the "theatre"'.match(/"\w+"/g) |
3 guxianbang OP @mooncakejs 匹配不到 |
4 clarkyi 2019-06-20 11:39:49 +08:00 "\w+"$ |
6 mooncakejs 2019-06-20 11:42:17 +08:00 @guxianbang 这是全匹配出来,找最后一个就好了。 只要最后一个就 'Last "week" I "went" to the "theatre"'.match(/"\w+"$/) |
7 opticaline 2019-06-20 11:44:02 +08:00 |
8 loryyang 2019-06-20 11:44:34 +08:00 re.match(r'[^"]*"[^"]*"[^"]*"([^"]*)".*', 'Last "week" I "went" to the "theatre"').group(1) 得到 went |
9 opticaline 2019-06-20 11:45:25 +08:00 @guxianbang 我觉得不是正则的问题,是你获取的不对 |
10 guxianbang OP 谢谢各位,我研究一下 |
11 pkookp8 2019-06-20 12:21:31 +08:00 via Android ^.*?".*?".*?"(.*?)" \1 |
12 ahaodady 2019-06-20 13:16:18 +08:00 解题问问,突然想到的一个问题 |
13 ahaodady 2019-06-20 13:17:15 +08:00 12345 使用 \d{2} 只能取到 12、34 我怎么取 23、45 呢 |
14 ahaodady 2019-06-20 13:21:28 +08:00 顺便回答题主,你的正则会取出所有引号里的内容,如果确定最后一项的话,在代码里取最后一条即可。 如果是编辑器里的话,结尾带个$ "([^"]+)"$ |
15 azh7138m 2019-06-20 13:24:55 +08:00 零宽断言? ^.*?(?<=".*?").*?"(.*?)" 先匹配一个"",然后取后面这个"" |
16 zhzbql 2019-06-20 14:58:57 +08:00 js 解法 /^.*?".*?".*?"(.*?)"/.exec('Last "week" I "went" to the "theatre"')[1] 或 'Last "week" I "went" to the "theatre"'.match(/".*?"/g)[1] |
17 hjq98765 2019-06-20 15:23:55 +08:00 |
18 ismyyym 2019-06-20 17:01:20 +08:00 python: import re str='Last "week" I "went" to the "theatre"' x=re.search('^.*?".*?".*?"(.*?)"',str ).group(1) #正数第二个”“ y=re.search('.*"(.*?)".*?".*?".*?$',str ).group(1) #倒数第二个”“ z=re.findall('"(.*?)"',str)[1] # 返回所有”“,取第二个 用对下面这些 ^ $ *? 开头 结尾 尽可能少 |