基础 - 匹配空白符

  • 作者:KK

  • 发表日期:2017.6.10


要点速读

  1. 直接这样一个空格就是直接指空格符号, +主是连续多个空格咯

  2. \s是匹配空白符,注意这个不是空格,是视觉上看到为空白的符号,包括tab缩进符号和其它特殊符号(看不见的)


JS代码

console.log('one two three'.match( /e two/ )[0]); //e two

//空格后有+,表示1个,或多个空格,于是也匹配
console.log('one two three'.match( /e +two/ )[0]); //e two

//空格也属于\s代指的空白范围嘛
console.log('one two three'.match( /e\stwo/ )[0]); //e two

//连续多个空格的字符串
console.log('one    two three'.match( /e\s+two/ )[0]); //e    two

var tab符= String.fromCharCode(9);
console.log(('one xxx two' + tab符+ 'three').match( /two\s+thr/ )[0]); //two thr

PHP代码

preg_match('#e two#', 'one two three', $matchResult1);

//空格后有+,表示1个,或多个空格,于是也匹配
preg_match('#e +two#', 'one two three', $matchResult2);

//空格也属于\s代指的空白范围嘛
preg_match('#e\s+two#', 'one two three', $matchResult3);

//连续多个空格的字符串
preg_match('#e\s+two#', 'one    two three', $matchResult4);

$tab符9);
preg_match('#two\s+thr#', 'one xxx two' . $tab符'three', $matchResult5);

header('Content-type:text/plain');
print_r([
	$matchResult1[0], //e two
	$matchResult2[0], //e two
	$matchResult3[0], //e two
	$matchResult4[0], //e    two
	$matchResult5[0], //two thr
]);