0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

「.」だけでは改行は無視される

Posted at

正規表現の有名な何でも屋「.」にも弱点はあります。
それは、仕様として「\n, \r, \u2028 or \u2029 には対応しない」となっていることです。
つまり、改行が来た瞬間「.」は自分の担当ではないと判断してしまうのです。

でも、優秀な仲間である s フラグを使えばこの弱点も補うことができます。

str.match(/^.*文字.*$/) -> 改行が入ると必ず null
str.match(/^.*文字.*$/s) -> 改行が入ってもヒット!

これで「.」も改行に負けない表現になりました。
めでたしめでたし。

... 実は「.」の代わりに「[^]」や「[\s\S]」でも良いのです

以下、Mozilla の docs より . の解説の引用

Has one of the following meanings:

  • Matches any single character except line terminators: \n, \r, \u2028 or \u2029. For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".
  • Inside a character class, the dot loses its special meaning and matches a literal dot.
    Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character class [^] can be used — it will match any character including newlines.

ES2018 added the s "dotAll" flag, which allows the dot to also match line terminators.

引用元:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?