Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

JavaScriptで正規表現 | パターンの設定回数

概要

パターンの設定回数について

構文

波括弧{}に数値を指定することで直前のパターンに対して
指定した回数の繰り返しを設定することが可能です。

{x}|直前のパターンをx回繰り返し
{x,}|直前のパターンをx回以上繰り返し
{x,y}|直前のパターンをx回以上y回以下繰り返し
{x,}?|?をつけると最短

<html>
<head>
<script language="javascript">
function executeRegExp(target,pattern) {
	regExp = new RegExp(pattern);
	document.write('input:target=' + target + ',pattern=' + pattern + '<br />');

	if (target.match(regExp)) {
	    document.write('<div style="color:green;">match as ' + target.match(regExp) + '</div>');
	} else {
	    document.write('<div style="color:red;">unmatch</div>');
	}
  document.write('<br />');
}

function execLoad() {
	pattern = '(test){2}';
	executeRegExp('testtes',pattern);
	executeRegExp('testtest',pattern);
	executeRegExp('testtesttest',pattern);

	pattern = '(test){2,}';
	executeRegExp('testtes',pattern);
	executeRegExp('testtest',pattern);
	executeRegExp('testtesttes',pattern);
	executeRegExp('testtesttest',pattern);

	pattern = '(test){2,3}';
	executeRegExp('testtes',pattern);
	executeRegExp('testtest',pattern);
	executeRegExp('testtesttes',pattern);
	executeRegExp('testtesttest',pattern);
	executeRegExp('testtesttesttest',pattern);

	pattern = '(test){2,}?';
	executeRegExp('testtes',pattern);
	executeRegExp('testtest',pattern);
	executeRegExp('testtesttes',pattern);
	executeRegExp('testtesttest',pattern);
}
</script>
</head>
<body onload="execLoad()">
</body>
</html>

結果

input:target=testtes,pattern=(test){2}
unmatch

input:target=testtest,pattern=(test){2}
match as testtest,test

input:target=testtesttest,pattern=(test){2}
match as testtest,test

input:target=testtes,pattern=(test){2,}
unmatch

input:target=testtest,pattern=(test){2,}
match as testtest,test

input:target=testtesttes,pattern=(test){2,}
match as testtest,test

input:target=testtesttest,pattern=(test){2,}
match as testtesttest,test

input:target=testtes,pattern=(test){2,3}
unmatch

input:target=testtest,pattern=(test){2,3}
match as testtest,test

input:target=testtesttes,pattern=(test){2,3}
match as testtest,test

input:target=testtesttest,pattern=(test){2,3}
match as testtesttest,test

input:target=testtesttesttest,pattern=(test){2,3}
match as testtesttest,test

input:target=testtes,pattern=(test){2,}?
unmatch

input:target=testtest,pattern=(test){2,}?
match as testtest,test

input:target=testtesttes,pattern=(test){2,}?
match as testtest,test

input:target=testtesttest,pattern=(test){2,}?
match as testtest,test