LoginSignup
0
0

More than 5 years have passed since last update.

正規表現:RegExp('Hello\sworld!')はマッチしない

Last updated at Posted at 2014-12-18

ハマったのでシェアします。

RegExpを使ってマッチさせるには以下のように書きます:

var re = new RegExp('Hello\\sworld!');

\s\Wといった正規表現を使う場合は、RegExpを使うとわかりにくくなってしまうので、個人的にはそういうときは以下のような書き方にしておいた方が良いと思います。

var re = /Hello\sworld!/;

なお、以下の追記2にある通りRegExpを使わないとできないこともあります。

追記1

mattnさんより以下のアドバイスをいただきました。ありがとうございます。

/Hello\sworld!/

は正規表現リテラルなので\sをエスケープする必要はありません(見たまま解釈されます)。

しかし

RegExpr('Hello\sworld!')

は文字列なのでRegExpに正しく\s(つまり\sの2文字)を渡すにはエスケープして\\sとする必要があります。

追記2

think49さんより以下のアドバイスをいただきました。ありがとうございます。

new RegExpは引数に変数を取れるのが利点です。
例えば、次のケースではnew RegExpを使わないと書けません。

var word = 'World!';
var reg = new RegExp('Hello\\s' + word);
console.log(reg.test('Hello World!')); // true

実用的には正規表現メタキャラクタのエスケープ処理が必要です


ブログやってます:Weed software

0
0
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0