2015年3月9日 星期一

Regular Expression-perl

文章轉
http://user.frdm.info/ckhung/b/re/rules.php
http://ind.ntou.edu.tw/~dada/cgi/Perlsynx.htm


/regular expression/expression modifier
● Modifiers:
  g: Match globally, i.e. find all occurrences. (搜尋全部)
  i: Makes the search case-insensitive. (區分大小寫)
  m: If the string has new-line characters embedded within it, the metacharacters ^ and $ will not work correctly. This modifier tells Perl to treat this line as a multiple line. (包含多行)
  o: Only compile pattern once.
  s: The character . matches any character except a new line. This modifier treats this line as a single line, which allows . to match a new-line character. 
  x: Allows white space in the expression.

● regular expression:
  ○特殊意義字元:
    \  跳脫字元
    ^ 以...為開頭
    . 除了換行的所有字串
    $ 以...為結尾
    | 或
    [] 搜尋誇號中字元
    () 括號

  ○ 字元數量關係:
    * 大於等於0次
    + 大於等於一次
    ? 0或1次
    {n} n次
    {n.} 至少n次
    {n, m} 最少n次,不超過m次

  ○ 特定字元:
    \r: carriage return(CR)
    \n: 換行
    \t: tab
    \w: 英文字母
    \W: 非英文字母
    \s white space
    \S non-white space
    \d: 數字
    \D: 非數字
    \b:  word boundary
    \B: non-word boundary
    \033: octal char
    \x1B: hex char


字串比對:

1. $string =~ /regular expression/expression modifier
2. if /regular expression/expression modifier

example:
(將C #define 轉換成verilog #parameter)

###read file
open($fp, "test1.c");
foreach $word (<$fp>)
{
 if ($word=~/^#define (\w+) (\d+)/)
 {
  $word =~ s/define (\w+) (\d+)\n/parameter/g;
  $word = $word . sprintf(" %s = 2'b%b\n",$1 , $2);;
  print "$word";
 }
}
close($fp);


字串取代:

s/PATTERN/REPLACEMENT/egimox



沒有留言:

張貼留言