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?

【正規表現】Unicode 単語境界アサーション\b

Posted at

正規表現の単語境界アサーション\bについてまとめた。

  • 早見表(例・説明は記事で説明している。)
正規表現 マッチするもの
\b \b{start}または\b{end}
\b{start} 左が\W|\Aかつ右が\w
\b{start-half} 左が\wかつ右が\W|\z
\b{end} 左が\W|\A
\b{end-half} 右が\W|\z

\b

単語と非単語の境目にマッチする。

「左が単語の一部でない」かつ「右が単語の一部である」位置もしくは、
「左が単語の一部である」かつ「右が単語の一部でない」位置にマッチする。

後で説明する\b{start}\b{end}を合わせたもの。

  • パターン: r"\btest"
  • テスト文字列(太字にマッチ): "hello test world mytest testtext--test"
  • パターン: r"test\b"
  • テスト文字列(太字にマッチ): "hello test world mytest testtext--test"

\b{start}

\<と同じ。

単語と非単語の境目の、単語の頭側の位置にマッチする。

「左が単語の一部でない」かつ「右が単語の一部である」位置にマッチする。

  • パターン: r"\b{start}test"
  • テスト文字列(太字にマッチ): "hello test world mytest testtext--test"
  • パターン: r"\b{start}-test"
  • テスト文字列(マッチ無し): "hello test world mytest testtext--test"

-は単語の一部とは判定されないため、r"\b{start}-"は何にもマッチしない

\b{start-half}

「左が単語の一部でない」位置にマッチする。

右が単語の一部であるかどうかは判定しない。

  • パターン: r"\b{start-half}test"
  • テスト文字列(太字にマッチ): "hello test world mytest testtext--test"
  • パターン: r"\b{start-half}-test"
  • テスト文字列(太字にマッチ): "hello test world mytest testtext--test"
    -もマッチしている)

-は単語の一部とは判定されないが、\b{start-half}は「左が単語でない」であればマッチするので、r"\b{start}-"が機能する。

\b{end}

\>と同じ

単語と非単語の境目の、単語のお尻側の位置にマッチする。

「右が単語の一部でない」かつ「左が単語の一部である」位置にマッチする。

\b{start}の逆なので例省略。

\b{end-half}

「右が単語の一部でない」位置にマッチする。

左が単語の一部であるかどうかは判定しない。

\b{start-half}の逆なので例省略。

参考

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?