0
1

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

概要

今更だけど、いつも忘れるのでよく使う正規表現の例を記録。

肯定、否定

(?=文字列A) 肯定。文字列Aを含む場合。
(?!文字列A) 否定。文字列Aを含まない場合。

OR, AND

(?=文字列A|文字列B) OR。文字列Aもしくは文字列Bを含む場合。
(?=文字列A)(?!文字列B) AND。文字列Aを含む且つ、文字列Bを含むない場合。

  • (?=GitHUB) -> GitHUBという文字列を含む
  • (?!GitHUB) -> GitHUBという文字列を含まない
  • (?=GitHUB|BitBucket) -> GitHUBもしくはBitBucketという文字列を含む
  • (?=GitHUB)(?=Enterprise) -> GitHUB且つEnterpriseという文字列を含む

実用例

実際に使う場合は、以下を組み合わせて使うことが多い。

^ 文字列の先頭を意味する。
$ 文末を意味する。
.* ワイルドカード。

  • ^(?=GitHUB).*$
    • GitHUBはレポジトリです -> マッチする
    • これが私のGitHUBレポジトリです -> マッチしない
  • ^(?=.*GitHUB).*$
    • GitHUBはレポジトリです -> マッチする
    • これが私のGitHUBレポジトリです -> マッチする

演習問題

文章のいずれかの位置に、GitHUBもしくはBitBucketを含む且つ、GHEもしくはEnterpriseを含まない正規表現を作れ。

解答

^(?=.*GitHUB|.*BitBucket)(?!.*GHE|.*Enterprise).*$

検証結果

文字列 matched
これが私のGitHUBのURLです。 Y
BitBucketのURLを教えてください。 Y
これは私のGitHUBのURLです。GitHUB Enterpriseではありません。 N
これは私のGitHUBのURLです。GHEではありません。 N

参考

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?