Source From Here
Introduction
I’m going to break it down, step by step, and take you through the concepts of regular expressions in Ruby and on to advanced techniques. My hope is that you’ll see the beauty of regular expressions and be able to move beyond the fear and intimidation and embrace them in your code.
Regular Expressions
A regular expression is just a pattern. It’s a pattern that a string either fits or it doesn’t. Programming Ruby 1.9 by Dave Thomas (more commonly known as the pickaxe book) sums up what you do with regular expressions in three words--test, extract, change. You can test a string to see if it matches your pattern. You can extract a string (or part of a string) that matches your pattern. And you can change a string, replacing parts that match your pattern with other text. Test, extract, change. So simple, yet so powerful.
Regular Expressions in Ruby
Ruby lets us take regular expressions to further heights. In Ruby, everything is an object. This includes regular expressions. Since you can send messages to objects, you can also send messages to regular expressions. You can also assign them to variables, pass them to methods, and more.
As of Ruby 1.9, Ruby uses the Oniguruma regular expressions library. It provides all the standard regular expressions features that of other Regular regular Expressions expressions library, but adds additional features and extensions. It handles complex, multi-byte characters (such as Japanese text) very well. A feature I particularly like is I can use /h and /H as shorthand for hexadecimal digits.
I recently found out Ruby 2.0 use a different regular expressions library, Onigmo. Onigmo is forked off of Oniguruma and will add even more features that can be harnessed by Ruby. It will be quite interesting to see what it brings. Regardless of what changes Onigmo makes, it won’t change the fundamental thing you do with a regular expression. You match your regular expression to a string. You compose a pattern and match a string to it.
Basic Matching
In most of my Ruby regular expressions, I use the =~ operator. This is Ruby’s basic pattern matching operator. When I use this operator, I’m asking Ruby "Does this string contain this pattern?". Let’s go through an example:
On the left side I have a regular expression, which in this case is the literal word force. On the other side I have a quote from one of my very favorite movies, Star Wars. "Use the force." When I run this, I’m asking Ruby if my pattern, on the left, exists in the string on the right. What’s nice is I can format it the opposite way if I want to.
I can have the string on the left and the regular expression on the right. I’m running the same function, just in different words - does my string contain my regular expression? Some people find this a little more readable. When I run this, it returns the character number where my match starts. In this case, my match for the pattern /force/ begins on the eighth character of my string.
I can also test if a string DOES NOT match a pattern by using the operator !~. This just returns a Boolean of true or false.
Operators are great for basic matching, knowing whether my string matches my regular expression or does not. But Ruby provides me much more information about my match. All I have to do is ask.
MatchData
The secret is to make my match a MatchData object. I create this object using the match method. Let’s say I have a string.
And I want to find out if this string contains the word force. I call the match method on my regular expression and pass it my string. When I run this, it returns an instance of the MatchData class for my particular match:
As of Ruby 1.9, I actually don’t have to start my match at the beginning of my string. I can pass a second argument, an integer, which means start my match on that character number.
In this case, it returns nil. In order to find a match for the word force, it needs to start matching earlier in the string. For this example, however, I’m just going to pass my string the first way. I have access to methods which give me MUCH more information about my match because my match is an instance of the MatchData class.
If I call to_s on my match, it will return the entire text of my match. If I call pre_match on my match, it will return the portion of my string that comes BEFORE my match:
If I call post_match on my match, it will return the portion of my string that comes AFTER my match:
All these methods (and there are several more) are quite useful. However, MatchData truly shines when it comes to capture groups, though. Capture groups are subexpressions within your regular expression. Let’s look at an example.
In order for a string to match this regular expression, it has to have any character appearing any number of times - that’s what the .* means- followed by the word force, followed by any character appearing any number of times. Notice that I have the first and last part of this expression in parentheses. These are called groups. When I run this match on my string, it will store matches for my groups in memory. I can access these groups and use the in other places in my code.
MatchData objects are a lot like arrays. I can access individual captures using bracket notation, similar to how I access individual elements of an array. If I runmy_match[1], I get my first capture group, "The ". Similarly, my_match[2] returnd my second capture group, " will be with you always".
Notice I didn’t start with my_match[0], like I would with the first element of an array. If I run my_match[0], rather than getting my first match, I get the full string I ran the match on.
It’s important to remember that although MatchData objects are similar to Arrays, they’re not actually arrays. If I try to call an array method like each on my MatchDataobject, I get back a no method error. I can easily fix this, however, by converting my my MatchData to an array using the to_a method.
Supplement
* Using Regular Expression in Ruby - Part2
* Using Regular Expression in Ruby - Part3
This is a blog to track what I had learned and share knowledge with all who can take advantage of them
標籤
- [ 英文學習 ]
- [ 計算機概論 ]
- [ 深入雲計算 ]
- [ 雜七雜八 ]
- [ Algorithm in Java ]
- [ Data Structures with Java ]
- [ IR Class ]
- [ Java 文章收集 ]
- [ Java 代碼範本 ]
- [ Java 套件 ]
- [ JVM 應用 ]
- [ LFD Note ]
- [ MangoDB ]
- [ Math CC ]
- [ MongoDB ]
- [ MySQL 小學堂 ]
- [ Python 考題 ]
- [ Python 常見問題 ]
- [ Python 範例代碼 ]
- [心得扎記]
- [網路教學]
- [C 常見考題]
- [C 範例代碼]
- [C/C++ 範例代碼]
- [Intro Alg]
- [Java 代碼範本]
- [Java 套件]
- [Linux 小技巧]
- [Linux 小學堂]
- [Linux 命令]
- [ML In Action]
- [ML]
- [MLP]
- [Postgres]
- [Python 學習筆記]
- [Quick Python]
- [Software Engineering]
- [The python tutorial]
- 工具收集
- 設計模式
- 資料結構
- ActiveMQ In Action
- AI
- Algorithm
- Android
- Ansible
- AWS
- Big Data 研究
- C/C++
- C++
- CCDH
- CI/CD
- Coursera
- Database
- DB
- Design Pattern
- Device Driver Programming
- Docker
- Docker 工具
- Docker Practice
- Eclipse
- English Writing
- ExtJS 3.x
- FP
- Fraud Prevention
- FreeBSD
- GCC
- Git
- Git Pro
- GNU
- Golang
- Gradle
- Groovy
- Hadoop
- Hadoop. Hadoop Ecosystem
- Java
- Java Framework
- Java UI
- JavaIDE
- JavaScript
- Jenkins
- JFreeChart
- Kaggle
- Kali/Metasploit
- Keras
- KVM
- Learn Spark
- LeetCode
- Linux
- Lucene
- Math
- ML
- ML Udemy
- Mockito
- MPI
- Nachos
- Network
- NLP
- node js
- OO
- OpenCL
- OpenMP
- OSC
- OSGi
- Pandas
- Perl
- PostgreSQL
- Py DS
- Python
- Python 自製工具
- Python Std Library
- Python tools
- QEMU
- R
- Real Python
- RIA
- RTC
- Ruby
- Ruby Packages
- Scala
- ScalaIA
- SQLAlchemy
- TensorFlow
- Tools
- UML
- Unix
- Verilog
- Vmware
- Windows 技巧
- wxPython
訂閱:
張貼留言 (Atom)
[Git 常見問題] error: The following untracked working tree files would be overwritten by merge
Source From Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 # git clean -d -fx 方案2: 今天在服务器上 gi...
-
前言 : 為什麼程序管理這麼重要呢?這是因為: * 首先,本章一開始就談到的,我們在操作系統時的各項工作其實都是經過某個 PID 來達成的 (包括你的 bash 環境), 因此,能不能進行某項工作,就與該程序的權限有關了。 * 再來,如果您的 Linux 系統是個...
-
屬性 : 系統相關 - 檔案與目錄 語法 : du [參數] [檔案] 參數 | 功能 -a | 顯示目錄中個別檔案的大小 -b | 以bytes為單位顯示 -c | 顯示個別檔案大小與總和 -D | 顯示符號鏈結的來源檔大小 -h | Hum...
-
來源自 這裡 說明 : split 是 Perl 中非常有用的函式之一,它可以將一個字串分割並將之置於陣列中。若無特別的指定,該函式亦使用 RE 與 $_ 變數 語法 : * split /PATTERN/,EXPR,LIMIT * split /...
沒有留言:
張貼留言