回答編集履歴
4
サンプルコードを追記
test
CHANGED
@@ -40,7 +40,13 @@
|
|
40
40
|
|
41
41
|
|
42
42
|
|
43
|
-
### サンプル
|
43
|
+
### サンプルコード
|
44
|
+
|
45
|
+
|
46
|
+
|
47
|
+
GitHubにサンプルコードをUPしました。
|
48
|
+
|
49
|
+
質問の要件は満たせていると思います。
|
44
50
|
|
45
51
|
|
46
52
|
|
@@ -50,11 +56,79 @@
|
|
50
56
|
|
51
57
|
|
52
58
|
|
59
|
+
```JavaScript
|
60
|
+
|
61
|
+
var string;
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
/**
|
66
|
+
|
67
|
+
* 「xxx」
|
68
|
+
|
69
|
+
*/
|
70
|
+
|
71
|
+
string = '「「「a」, 「「b」」, 「「c」「d」」, 「「「e」「f」」」, 「「「g」」「「h」」」';
|
72
|
+
|
73
|
+
console.log(JSON.stringify(findCorrespondingFromString(string, '「', '」'))); // ["「a」","「「b」」","「「c」「d」」","「「「e」「f」」」","「「「g」」「「h」」」"]
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
/**
|
78
|
+
|
79
|
+
* <<xxx>>
|
80
|
+
|
81
|
+
*/
|
82
|
+
|
83
|
+
string = '<<a>>,<<<<b>>>>,<<<<c>><<d>>>>';
|
84
|
+
|
85
|
+
console.log(JSON.stringify(findCorrespondingFromString(string, '<<', '>>'))); // ["<<a>>","<<<<b>>>>","<<<<c>><<d>>>>"]
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
/**
|
90
|
+
|
91
|
+
* <div>xxx</div>
|
92
|
+
|
93
|
+
*/
|
94
|
+
|
95
|
+
string = `<div id="parent">
|
96
|
+
|
97
|
+
<p>text</p>
|
98
|
+
|
99
|
+
<div class="child">
|
100
|
+
|
101
|
+
<p>text</p>
|
102
|
+
|
103
|
+
<p>text</p>
|
104
|
+
|
105
|
+
<div class="grandson">
|
106
|
+
|
107
|
+
<p>text</p>
|
108
|
+
|
109
|
+
</div>
|
110
|
+
|
111
|
+
<div class="grandson">grandson2</div>
|
112
|
+
|
113
|
+
</div>
|
114
|
+
|
115
|
+
<div class="child">child2</div>
|
116
|
+
|
117
|
+
</div>`;
|
118
|
+
|
119
|
+
console.log(JSON.stringify(findCorrespondingFromString(string, '<div(?:\\s[^>]*)?>', '</div>'))); // [<div id="parent">...</div>]
|
120
|
+
|
121
|
+
```
|
122
|
+
|
123
|
+
|
124
|
+
|
53
125
|
### 更新履歴
|
54
126
|
|
55
127
|
|
56
128
|
|
57
|
-
- 2017/05/13 02:13 [サンプル] の節を追記。
|
129
|
+
- 2017/05/13 02:13 [サンプルコード] の節を追記。
|
130
|
+
|
131
|
+
- 2017/05/13 08:04 サンプルコードを追記。
|
58
132
|
|
59
133
|
|
60
134
|
|
3
\[サンプル\] の節を追記。
test
CHANGED
@@ -40,4 +40,22 @@
|
|
40
40
|
|
41
41
|
|
42
42
|
|
43
|
+
### サンプル
|
44
|
+
|
45
|
+
|
46
|
+
|
47
|
+
- [find-corresponding-from-string.js - JSFiddle](https://jsfiddle.net/9cpdkfd3/)
|
48
|
+
|
49
|
+
- [find-corresponding-from-string.js - GitHub](https://gist.github.com/think49/53b4a2cedfcff3c1a1ea40390a7ff3d8)
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
### 更新履歴
|
54
|
+
|
55
|
+
|
56
|
+
|
57
|
+
- 2017/05/13 02:13 [サンプル] の節を追記。
|
58
|
+
|
59
|
+
|
60
|
+
|
43
61
|
Re: hatena19 さん
|
2
markdown修正
test
CHANGED
@@ -22,7 +22,9 @@
|
|
22
22
|
|
23
23
|
3階層以上の括弧に対応する為には開始文字(`「`)の数と終了文字(`」`)の回数が一致するまで再帰的にマッチさせる必要があります。
|
24
24
|
|
25
|
+
`RegExp#exec` で再帰的にマッチさせれば可能です。
|
26
|
+
|
25
|
-
|
27
|
+
が、注意点として `「「「a」` のように対応する括弧で閉じられていないパターンの為に**バックトラック処理**(マッチに失敗した場合に失敗前の場所まで戻ってマッチをやり直す)が必要になります。
|
26
28
|
|
27
29
|
|
28
30
|
|
1
不要な文言削除
test
CHANGED
@@ -1,7 +1,3 @@
|
|
1
|
-
>ただし、関数スコープがローカル変数を参照し続ける場合は別です。
|
2
|
-
|
3
|
-
|
4
|
-
|
5
1
|
### 括弧が2階層までの場合
|
6
2
|
|
7
3
|
|