2010年4月23日

Regular Expression 語法

在很多程式中見到看起來很怪的語法, 中文稱為「正規表達式 」,例如
 
([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})
代表 yyyy-mm-dd 的日期格式, 或
 
a[0-9]*\.c
代表 a12.c,a932.c 等以 a 開頭, 以 .c 結尾, 中間只能是數字, 的所有字串
還滿聰明的一個做法
 
參見
特別要抓 unicode 中文的話, 看這裡

 
  它使用「/xxx/u」,在最後加上「u」,以這方式支援 UTF-8,
 
#!/usr/bin/php -q
$a = "def:123:這是:AB=你好!";
$pattern = 
'/123:([\x{4e00}-\x{9fff}]+):[A-B]*/u';
preg_match($pattern, 
$a,$match);
echo $match[0];
?> 
 
ASP 中使用:
例 1
Function RegExpTest(patrn, strng) 
   Dim regEx, retVal ' 建立變量。 
   Set regEx = New RegExp ' 建立正則表達式。 
   regEx.Pattern = patrn ' 設置模式。 
   regEx.IgnoreCase = False ' 設置是否區分大小寫。 
   retVal = regEx.Test(strng) ' 執行搜索測試。 
   If retVal Then 
      RegExpTest = "找到一個或多個匹配。" 
   Else 
      RegExpTest = "未找到匹配。" 
   End If 
End Function  
 
例 2
 
s1="This equation {x} + {y} = {x+y}
"
x=100
y=200
response.write "====>" & Var2Value(s1) & "
" 
function Var2Value(var_name)
   Var2Value = Txt2Value(var_name, 1)
end Function
function Txt2Value(str, level)
   dim regEx, Matches, Result
   Set regEx = new RegExp
   select case level
          case 0 regEx.Pattern = "\{([\w\(\)]+)\}" '變數名有效判斷
          case 1 regEx.Pattern = "\{([\w+\-\*/\\<>=\(\)]+)\}" '變數名及運算符號有效
          'case 2 regEx.Pattern = "\{([\w\s\(\)]+)\}" '除換行符外的所有字符有效
          case else exit function
   end select
   regEx.IgnoreCase = true
   regEx.Global = true
   Set Matches = regEx.Execute(str)
   Result = str
   'response.write Matches.Count
   For Each Match In Matches
      Result = Replace(Result, Match.Value, GetVar(Match.SubMatches(0)))
   Next
   set Matches = nothing
   set regEx = nothing
   Txt2Value = Result
end function