SlideShare a Scribd company logo
1 of 22
Ruby 正規表現
POSIX 文字クラス, Unicode プロパティ
ユニークビジョン株式会社
中野 隆行
はじめに
エンジニアであれば正規表現には1度は出会ったことがあるはずです。
同じことを表現するにしても様々な書き方が出来ます。
/[0-9]/ = /¥d/
今回は Ruby の正規表現(というか 鬼雲ライブラリ)で使える POSIX 文字クラス
と Unicode プロパティ という記法に関して話します。
POSIX 文字クラス
とりあえずドキュメント情報
>文字クラスの中でしか用いることができません。
>これらは [:クラス名:] という記法を持ちます。また、[:^クラス名:]という記法
でその否定を意味します。
Ruby 2.7.0 リファレンスマニュアル 正規表現
使用可能な文字クラスの一覧も記載があります。
例
個人的には [:space:] が便利です。
以前、Ruby で文章中の空白を削除するという作業が必要になりました。
まず最初に使ったのが String#strip
文字列先頭と末尾の空白を削除してくれます。
空白文字の定義は " ¥t¥r¥n¥f¥v"
残念なことに全角スペースが含まれていません。
というわけでこうなります
また、文中の空白も削除しません。(これは一長一短)
なので、次に [:space:] の力を借りました。
puts ' ←半角スペース'.strip #←半角スペース
puts ' ←全角スペース'.strip # ←全角スペース
[:space:] の定義はこんな感じ
● [:space:] 空白、改行、復帰 (Space_Separator | Line_Separator | Paragraph_Separator | 0009 | 000A |
000B | 000C | 000D | 0085)
Space_Separator とか Line_Separator とかは Unicode 一般カテゴリのことです。
このカテゴリに含まれる文字がこの文字クラスに含まれます。
後の 0009 とかは文字コードです。タブとか復帰とかの制御文字とか。
全角スペース(和字間隔 - Ideographic Space) は Space_Separator に含まれていま
す。
というわけで、こうなります。
無事全角スペースも除去できました。
この場合文中のスペースも取り除くので、文頭 文末のみ除去したい場合適当に正
規表現を調節しましょう。
puts ' ←半角スペース'.gsub(/[[:space:]]/, '') #←半角スペース
puts ' ←全角スペース'.gsub(/[[:space:]]/, '') #←全角スペース
puts ' ←半 角 ス ペ ー ス'.gsub(
/^[[:space:]]*|[[:space:]]*$/, ''
)#←半 角 ス ペ ー ス
POSIX 文字クラスの注意点
とある記事(正規表現クラス[:alnum:]の罠)で一部 POSIX 文字クラスの挙動に関し
て議論になったことがあります。
それが [:alpha:] と [:alnum:]
これらがかなり誤解の種をはらんでいて、しかもドキュメントがその一翼を担っ
ています。
● [:alnum:] 英数字 (Letter | Mark | Decimal_Number)
● [:alpha:] 英字 (Letter | Mark)
以上が Ruby 2.7.0 リファレンスマニュアル の記述。
非常に簡潔な定義ですが、初めて見た人はきっと勘違いします。
これらは「ひらがな」「かたかな」「漢字」なども範囲に含んでいます。
[a-zA-Z] の気持ちで [:alpha:] を使うと失敗します。
こんな感じ
なぜこうなるか
ドキュメントを改めて確認しましょう
● [:alnum:] 英数字 (Letter | Mark | Decimal_Number)
● [:alpha:] 英字 (Letter | Mark)
括弧内に記載されているのは Unicode カテゴリです。Letter は
Letter (L): lowercase (Ll), modifier (Lm), titlecase (Lt), uppercase (Lu), other (Lo)
と定義されています。
数字、記号類以外の世に遍く文章を記述する文字全般が含まれます。
気をつけて使いましょう。
Unicode プロパティ
POSIX 文字クラスと似ています。
が、コレ自体が文字クラスの略記法なので [] で囲む必要はありません。
Unicode プロパティで正規表現の文字クラスを指定できます。
こちらのほうが定義の範囲が細かく、特定のジャンルの文字に絞り込みやすいで
す。
例
利点
正規表現で漢字が入力に含まれているかを探したことはありますか?
ネットでよく見かける表現はこんな感じ
/[一-龠]/ とか /[一-龥]/ とか(Unicode の話)
大体これで一般的な漢字はカバー出来ています。この文字クラスに収まらない漢
字を入力してくるユーザーもそうそういないでしょう。
ところでこんなものがあります。
新元号、令和の令です。この漢字は韓国語にも存在して、右のがそれです。
普通、日本人が日本語キーボードで入力してきている内はあんな漢字がシステム
に流れてくることも無いはずだが、それでも拾いたい場合に使える。
あとこんなものも。
Unicode 的に「ひらがな」の称号を与えられた文字は 300 を超えます。
[ぁ-ん]と違い、それら全てにしっかりマッチします。
使えるプロパティ
一覧 が公式に用意されています。
Unicode 一般カテゴリや script プロパティなどを指定できます。
POSIX brackets などもあるので、POSIX 文字クラスと同じ様なことも出来ます。
少し気をつけなければならないのは 長音記号 「ー」です。
長音記号の Unicode 情報を調べると
「Block:Katakana, U+30A0 - U+30FF」 と表示されます。
一瞬、カタカナブロックだから /¥p{Katakana}/ でマッチしてほしくなります
が、onigmo ライブラリがこの記述で参照するのはブロックではなく script プロパ
ティの Katakana です。
長音記号は Katakana script には含まれていません Common script です。
なので /[¥p{Katakana}ー]/ こんな感じに別途記述します。
あるいは /¥p{In_Katakana}/と書いて、Block プロパティのカタカナを参照し
ましょう。
個人的な意見
昔は POSIX 文字クラスビミョーと思ってましたが、いまはどっちも便利なもの
だと思っています。ただし一長一短です。
あとから /¥p{Hiragana}/ このコードを触る人間が、「ゟ」こんなものがマッ
チすると思うでしょうか?
あるいは /¥p{Katakana}/ このコードに「ヿ」こんなものがマッチすると思う
でしょうか?
把握しきれない文字にマッチしてくれる文字クラスということは、
他のコーダーが何にマッチする正規表現なのか把握しきれないということにもな
りえます。
コメントにて unicode のドキュメントに誘導するなど、プロジェクト内で誤解の
無いように運用したい。
(ちなみにこれらは Ruby (onigmo ライブラリ)独自の機能ではありません。)
(細かい実装の差異はありますが、他の正規表現エンジンでも利用できる場合があ
ります。)

More Related Content

Recently uploaded

TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdftaisei2219
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略Ryo Sasaki
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものですiPride Co., Ltd.
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Yuma Ohgami
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Danieldanielhu54
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A surveyToru Tamaki
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...Toru Tamaki
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNetToru Tamaki
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムsugiuralab
 

Recently uploaded (9)

TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdf
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものです
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Daniel
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システム
 

Featured

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellSaba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming LanguageSimplilearn
 

Featured (20)

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
 

Ruby regexp