DEV Community

kaede
kaede

Posted on • Updated on

よく使う正規表現の整理 -- 文頭文末やある文字の前後など

why

正規表現を書くとき、毎回チンタラ書いているので。
まとめて洗い出したくなった。

https://www.youtube.com/watch?v=rhzKDrUiJVk

この動画を参考に学んだ。

regexr.com で実行した。

{char} は任意の文字ってつもりで書いている


{char}* で 0 文字以上の char を検出

Image description

do*g で d と g の中に挟まれている o がなん文字でも検出する。

間に挟まれているのが o 以外だと検出されない。


.* で全ての文字を検出

https://www-creators.com/archives/2737

Image description

d.*g で d と g の間に何が含まれていても検知できる。


\w で全ての単語を抽出

Image description

バックスラッシュと w で単語を抽出できる

^,$ とは組み合わせられない

Image description

大文字の W を使うと単語以外を抽出できる


\s で全てのスペースを抽出

Image description

Image description

バックスラッシュと s でも同じくスペースとスペース以外を抽出できる。

これでハイフンやアンダーバーなどに置換できるだろう。


^{char}/gm で各行の先頭の char を抽出する

https://www.tohoho-web.com/js/regexp.htm

/g は 2 番目のヒット以降も検知するオプション
/m は 2 行目以降も検知するオプション

/^I/gm
Enter fullscreen mode Exit fullscreen mode

Image description

これで各行の行頭の I だけ検知できる。


{char}$/gm で各行の末尾の char を抽出する

https://www.tohoho-web.com/js/regexp.htm

/dogs$/gm
Enter fullscreen mode Exit fullscreen mode

Image description

同様に dog$ で行末の dog だけ検知できた。
文末の , だけ検知して置換したりするのは便利そう


(?<={char})(.*) で char より後の全ての文字列を取る

https://if.t0m0t.com/post-220/

なんでもナレッジ さんを参考にした。

Image description

(?<=:)(.*)
Enter fullscreen mode Exit fullscreen mode

これで : の後の文字列を抽出できる。

Image description

?<={char} は char 以降の文字列って意味らしい。

(?<=:)..
Enter fullscreen mode Exit fullscreen mode

なので、(.*) の[全ての文字列」という表現を変えて
(..) の「二文字」という表現にすると

Image description

: の後の 2 文字が取れる。


(.*)(?={char}) で char より前の文字列を全て取る

おなじく なんでもナレッジ さんの記事を参考にする

(.*) で全ての文字を取るのは同じ。
これに組み合わせる条件として

?={char} を使う

Image description

これで char より前の文字という検索条件になる。

(.*)(?=:)
Enter fullscreen mode Exit fullscreen mode

Image description

これで : より前の文字列が取れた。

?=hoge が hoge より前で
?<=hoge が hoge より後なのは見た目に反する(感想)

hoge<? と ?<hoge だったらいいのに〜〜〜


まとめ

  • (.) で 1 文字
  • (.*) で全ての文字
  • (o*) で o 文字以上の o
  • \w, \s で全ての単語, 全てのスペース
  • ^hoge/gm で各行の先頭の hoge
  • hoge$/gm で各行の文末の hoge
  • (?<=hoge)(.*) で hoge より後全て
  • (.*)(?=hoge) で hoge より前全て

これらが正規表現で取得できる。

Top comments (0)