如何用正则表达式匹配第二个引号里的内容?

2019-06-20 11:13:45 +08:00
 guxianbang

当一个句子中有多对引号的时候,例如:

Last "week" I "went" to the "theatre"

正则表达式"[^"]+"只能匹配最后一个引号里的内容:theatre

我想匹配第二个引号里的内容( went ),该怎么写规则呢?

6022 次点击
所在节点    程序员
18 条回复
choury
2019-06-20 11:17:35 +08:00
多匹配点,然后别的不捕获
mooncakejs
2019-06-20 11:22:21 +08:00
'Last "week" I "went" to the "theatre"'.match(/"\w+"/g)
guxianbang
2019-06-20 11:31:25 +08:00
@mooncakejs 匹配不到
clarkyi
2019-06-20 11:39:49 +08:00
"\w+"$
clarkyi
2019-06-20 11:40:34 +08:00
@clarkyi 这一条也不行
mooncakejs
2019-06-20 11:42:17 +08:00
@guxianbang 这是全匹配出来,找最后一个就好了。
只要最后一个就 'Last "week" I "went" to the "theatre"'.match(/"\w+"$/)
opticaline
2019-06-20 11:44:02 +08:00

```
var re = /"[^"]+"/g;
var s = 'Last "week" I "went" to the "theatre"';
var m;

do {
m = re.exec(s);
if (m) {
console.log(m[0]);
}
} while (m);
```
loryyang
2019-06-20 11:44:34 +08:00
re.match(r'[^"]*"[^"]*"[^"]*"([^"]*)".*', 'Last "week" I "went" to the "theatre"').group(1)
得到 went
opticaline
2019-06-20 11:45:25 +08:00
@guxianbang 我觉得不是正则的问题,是你获取的不对
guxianbang
2019-06-20 11:59:20 +08:00
谢谢各位🙏,我研究一下
pkookp8
2019-06-20 12:21:31 +08:00
^.*?".*?".*?"(.*?)"
\1
ahaodady
2019-06-20 13:16:18 +08:00
解题问问,突然想到的一个问题
ahaodady
2019-06-20 13:17:15 +08:00
12345

使用 \d{2}
只能取到 12、34
我怎么取 23、45 呢
ahaodady
2019-06-20 13:21:28 +08:00
顺便回答题主,你的正则会取出所有引号里的内容,如果确定是最后一项的话,在代码里取最后一条即可。

如果是编辑器里的话,结尾带个$

"([^"]+)"$
azh7138m
2019-06-20 13:24:55 +08:00
零宽断言?
^.*?(?<=".*?").*?"(.*?)"
先匹配一个"",然后取后面这个""
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]
hjq98765
2019-06-20 15:23:55 +08:00
@ahaodady 零宽断言

以 python 为例:

import re
re.findall('(?=(\d{2}))','12345')
# ['12', '23', '34', '45']
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] # 返回所有”“,取第二个


用对下面这些
^ $ *?
开头 结尾 尽可能少

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/575752

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX