2008年2月19日 星期二

Regular Expression - 字元類別(character class)

以[]來包含一個字元類別.
以 - 來表示一個範圍.
^ : 反集合
\s : whitespace
[^a-zA-Z\s] : 不是字母(A-Za-z)與空白(\s)的字元.
$_ : m//,s/// 預設作用物件
| : (alternative match patterns)多選一的符合樣式,like or.
數量元(quantifier),指定樣式比對一定的數目.

max min
+ +? 符合一次 或多次
* *? 符合零次 或多次
? ?? 符合零次 或一次

ex1.將不是大寫字母開頭的單字,存成陣列.
$_ = "Perl is the best language.";
@a = m/\b[^A-Z]+\b/g;
print @a;

ex2. 讀入quit,exit,stop 程式終止
while(<>){
if(m/quit|exit|stop/){exit;}
}

ex3.將一個或一個以上的空白,以一個空白來取代
$text = "Hello form Perl.";
$text=~s/ +/ /g;
print $text;

沒有留言:

關於我自己

Aspire freedom , Hope to do Soming make self complete ~