You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can put both kinds of quotes in the square brackets: `pattern:['"](.*?)['"]`, but it would find strings with mixed quotes, like `match:"...'`and`match:'..."`. That would lead to incorrect matches when one quote appears inside other ones, like in the string `subject:"She's the one!"`:
15
+
我们可以将两种引号放在方括号中:`pattern:['"](.*?)['"]`,但它会找到带有混合引号的字符串,例如 `match:"...'`和`match:'..."`。当一种引号出现在另一种引号内,比如在字符串 `subject:"She's the one!"` 中时,便会导致不正确的匹配:
16
16
17
17
```js run
18
18
let str =`He said: "She's the one!".`;
19
19
20
20
let regexp =/['"](.*?)['"]/g;
21
21
22
-
//The result is not what we'd like to have
22
+
//不是我们想要的结果
23
23
alert( str.match(regexp) ); // "She'
24
24
```
25
25
26
-
As we can see, the pattern found an opening quote `match:"`, then the text is consumed till the other quote `match:'`, that closes the match.
To make sure that the pattern looks for the closing quote exactly the same as the opening one, we can wrap it into a capturing group and backreference it: `pattern:(['"])(.*?)\1`.
0 commit comments