Skip to content

Instantly share code, notes, and snippets.

@think49
Last active November 4, 2018 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/071350bcc987d82dd836885ea6f5c0d4 to your computer and use it in GitHub Desktop.
Save think49/071350bcc987d82dd836885ea6f5c0d4 to your computer and use it in GitHub Desktop.
match-all-character-pair.js: 検索対象文字列から、指定した「開始文字」「終了文字」の対応範囲となる文字列を検索し、配列で返します

match-all-character-pair.js

概要

検索対象文字列から、指定した「開始文字」「狩猟文字」の対応関係からなるString値を要素に持つ配列を返します。 (※テキストエディタの「対応する括弧の強調表示」をイメージすると、分かりやすいかもしれません)

使い方

matchAllCharacterPair(string, startChar, endChar)

第一引数に検索対象となるString値を指定し、第二引数に開始の1文字、第三引数に終了の1文字を指定して検索結果を配列で返します。

matchAllCharacterPair('[a][[b]][[[c]]]', '[', ']');  // ["[a]","[[b]]","[[[c]]]"]

第二引数、第三引数に指定するString値は1文字でなければなりません。2文字以上を指定した場合は、初めの1文字を対象として扱います。

matchAllCharacterPair('<a><b>', '<a', '>');  // ["<a>", "<b>"] (※第二引数に "<" が指定されたものとして扱う)

参考リンク

/**
* match-all-character-pair.js
* Match the corresponding characters.
*
* @version 1.0.0
* @author think49
* @url https://gist.github.com/think49/071350bcc987d82dd836885ea6f5c0d4
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
function matchAllCharacterPair (string, startChar, endChar) {
'use strict';
startChar = String(startChar)[0];
endChar = String(endChar)[0];
var reg = new RegExp('[\\' + startChar + '\\' + endChar + ']|[^\\' + startChar + '\\' + endChar + ']+', 'g'), pairList = [], nestLevel = 0, matchString, pair = '', result;
while (result = reg.exec(string)) {
matchString = result[0];
switch (matchString) {
case startChar:
++nestLevel;
pair += matchString;
break;
case endChar:
if (nestLevel === 0) {
break;
}
pair += matchString;
if (--nestLevel === 0) {
pairList.push(pair);
pair = '';
}
break;
default:
if (nestLevel) {
pair += matchString;
}
}
}
return pairList;
}
<!DOCTYPE html>
<head>
<title>test</title>
<style>
</style>
</head>
<body>
<script src="match-all-character-pair-1.0.0.js"></script>
<script>
'use strict';
console.assert(JSON.stringify(matchAllCharacterPair('[a],[[b]],[c[c[c]c]c],[d[d]d[d]d]', '[', ']')) == '["[a]","[[b]]","[c[c[c]c]c]","[d[d]d[d]d]"]');
console.assert(JSON.stringify(matchAllCharacterPair('(e))(f)', '(', ')')) === '["(e)","(f)"]')
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment