Tbpgr Blog

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

JavaScriptで正規表現 | アルファベット、数字、アンダーバーの指定

概要

アルファベット、数字、アンダーバーの指定について

構文

[\\w]. = アルファベット、数字、アンダーバー
[\\w]. = アルファベット、数字、アンダーバー以外

<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 = '[\\w]';
	executeRegExp('a',pattern);
	executeRegExp('A',pattern);
	executeRegExp('0',pattern);
	executeRegExp('_',pattern);
	executeRegExp('あ',pattern);
	executeRegExp('ア',pattern);
	executeRegExp('亜',pattern);
	executeRegExp('[',pattern);

  document.write('---------------------------------------------<br />');

	pattern = '[\\W]';
	executeRegExp('a',pattern);
	executeRegExp('A',pattern);
	executeRegExp('0',pattern);
	executeRegExp('_',pattern);
	executeRegExp('あ',pattern);
	executeRegExp('ア',pattern);
	executeRegExp('亜',pattern);
	executeRegExp('[',pattern);
}
</script>
</head>
<body onload="execLoad()">
</body>
</html>

出力

input:target=a,pattern=[\w]
match as a

input:target=A,pattern=[\w]
match as A

input:target=0,pattern=[\w]
match as 0

input:target=_,pattern=[\w]
match as _

input:target=あ,pattern=[\w]
unmatch

input:target=ア,pattern=[\w]
unmatch

input:target=亜,pattern=[\w]
unmatch

input:target=[,pattern=[\w]
unmatch

---------------------------------------------
input:target=a,pattern=[\W]
unmatch

input:target=A,pattern=[\W]
unmatch

input:target=0,pattern=[\W]
unmatch

input:target=_,pattern=[\W]
unmatch

input:target=あ,pattern=[\W]
match as あ

input:target=ア,pattern=[\W]
match as ア

input:target=亜,pattern=[\W]
match as 亜

input:target=[,pattern=[\W]
match as [