Tbpgr Blog

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

JavaScriptで正規表現 | 複数の文字列へのマッチング

パンくず

JavaScriptで正規表現
複数の文字列へのマッチング

概要

複数の文字列へのマッチングについて

構文

角括弧[]で文字列パターンを囲うことで任意の文字列へのマッチングが可能です。

パターン一覧

構文 内容
a-z アルファベット小文字のa〜zをあらわす
A-Z アルファベット大文字のA〜Zをあらわす
0-9 半角数字をあらわす
^A-Z アルファベット大文字のA〜Z以外をあらわす
0-9a-zA-Z 半角数字,アルファベット大文字小文字をあらわす

<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() {
  document.write('<b>英小文字</b><br />');
	pattern = '[a-z]';
	executeRegExp('a',pattern);
	executeRegExp('z',pattern);
	executeRegExp('0',pattern);
	executeRegExp('A',pattern);

  document.write('<b>英大文字</b><br />');
	pattern = '[A-Z]';
	executeRegExp('A',pattern);
	executeRegExp('Z',pattern);
	executeRegExp('0',pattern);
	executeRegExp('a',pattern);

  document.write('<b>数字</b><br />');
	pattern = '[0-9]';
	executeRegExp('1',pattern);
	executeRegExp('9',pattern);
	executeRegExp('a',pattern);
	executeRegExp('A',pattern);

  document.write('<b>英大文字以外</b><br />');
	pattern = '[^A-Z]';
	executeRegExp('A',pattern);
	executeRegExp('Z',pattern);
	executeRegExp('a',pattern);
	executeRegExp('1',pattern);

  document.write('<b>数字、英大文字小文字</b><br />');
	pattern = '[0-9a-zA-Z]';
	executeRegExp('A',pattern);
	executeRegExp('Z',pattern);
	executeRegExp('a',pattern);
	executeRegExp('1',pattern);
	executeRegExp('#',pattern);
}
</script>
</head>
<body onload="execLoad()">
</body>
</html>

結果

英小文字
input:target=a,pattern=[a-z]
match as a

input:target=z,pattern=[a-z]
match as z

input:target=0,pattern=[a-z]
unmatch

input:target=A,pattern=[a-z]
unmatch

英大文字
input:target=A,pattern=[A-Z]
match as A

input:target=Z,pattern=[A-Z]
match as Z

input:target=0,pattern=[A-Z]
unmatch

input:target=a,pattern=[A-Z]
unmatch

数字
input:target=1,pattern=[0-9]
match as 1

input:target=9,pattern=[0-9]
match as 9

input:target=a,pattern=[0-9]
unmatch

input:target=A,pattern=[0-9]
unmatch

英大文字以外
input:target=A,pattern=[^A-Z]
unmatch

input:target=Z,pattern=[^A-Z]
unmatch

input:target=a,pattern=[^A-Z]
match as a

input:target=1,pattern=[^A-Z]
match as 1

数字、英大文字小文字
input:target=A,pattern=[0-9a-zA-Z]
match as A

input:target=Z,pattern=[0-9a-zA-Z]
match as Z

input:target=a,pattern=[0-9a-zA-Z]
match as a

input:target=1,pattern=[0-9a-zA-Z]
match as 1

input:target=#,pattern=[0-9a-zA-Z]
unmatch