Software engineering notes

Regular Expression

需要被脫逸的符號 :

左中括號([)需脫逸 , 但右中括號(])不需脫逸 , 左下到右上的斜線(/)也需要脫逸

符號對照 :

比對方式 :

語法結構 :

re = /pattern/flag
re = new RegExp("pattern", "flag");

pattern 是正規表示法比對規則,flag 則是比對的方式

Examples

數量 : 不能為0的正整數

/^[1-9]\d*$/

價格 : 0 或是正整數

/^(0|[1-9]\d*)$/

0 : 零, | : 或者, [1-9]\d* : 正整數

整數或最多兩位小數

/^(0|[1-9]\d*)(\.\d{1,2})?$/

中文姓名 : 檢查中文字2~5個字

javascript :

/^[\u4e00-\u9fa5]{2,5}$/

中文的正則, 如果把javascript語法搬到php會出現 Warning : preg_match()[function.preg-match] : Compilation failed : PCRE does not support \L , \I , \N , \U or \u at offset 9 的錯誤

解決方法 : 將\u改成\x , 並且將後面的中文代碼用{ } 括起來 , 在表示法最後的斜線後加一個 u

php :

/^[\x{4e00}-\x{9fa5}]{2,5}$/u

email : email格式

/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/

室內電話 : 離鳥區碼最多4碼 , 後面最少5碼最多8碼 . 例如 : 02-42365514

/^[0]{1}[0-9]{1,3}[-]{1}[0-9]{5,8}$/     (前面4碼後面8碼 , 會超過10碼條件 , 所以要再判斷一次 , 如下一行)
/^[0-9-]{10,11}$/                        (共10或11碼)

要驗證兩次 , 如果下次有空的話再改成一行表示法 , 因為很久沒用這個 , 所以有點懶

地址 : 禁止中,英,數,減號( - )以外的字元,至少要連續中文4個字,至少一位數字,字元數共8~40位

/^(?!.*[^\u4e00-\u9fa5a-zA-Z0-9-])(?=.*[\u4e00-\u9fa5]{4,})(?=.*\d).{8,40}$/

網址

/((http[s]{0,1}|ftp):\/\/[a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,4})(:\d+)?(\/[a-zA-Z0-9\.\-~!@#$%^&amp;*+?:_\/=<>]*)?)/g
or
((http[s]{0,1}|ftp):\/\/[a-zA-Z0-9\.\-\_\/]+\.([a-zA-Z]{2,4})(:\d+)?(\/[a-zA-Z0-9\.\-~!@#$%^&amp;*+?:_\/=<>]*)?)

正規取代驗證多餘空白:

^(.*[^\s])?\s+$`    取代成 `\1

驗證密碼 至少各一位英文字母、數字,共8~12位 :

/^(?!.*[^a-zA-Z0-9])(?=.*\d)(?=.*[a-zA-Z]).{8,12}$/

解析: 第一個是判斷不能有小寫及數字以外的字元,第二個是數字至少要有一個,第三個是小寫至少要有一個,第四個是要8~12位

不允許逗號及從頭到尾都是0

^(?!.*[,])(?!.*(^0+$))(.*)$

含有中文字元

(.*?\p{Han})

前後不能有空白

^[^\s]+[A-Za-z\s]{2,21}[^\s]+$

結果 :

[^\s]+ 代表不能有空白, 所以在頭尾各放一個去限制頭尾不能有空白

檢查 05:30 時間格式

^([0-1]+[0-9]|2[0-3]):[0-5][0-9]$

只 match 中間的部份

字串

import javax.faces.application.FacesMessage;

regex

(?<=import ).*?(?=;)

結果

javax.faces.application.FacesMessage

\K example

$ echo 'hello world' | grep -oP 'hello \K(world)'
world
$ echo 'hello world' | grep -oP 'hello (world)'
hello world

配對尾數後面是 0+

^(\d+[1-9]\.?|\d+\.\d+[1-9])(0+)$

配對結果

allowed me any chars , but it cant allowed (0-9) numbers

^([^0-9]*)$

不允許字串 not

^(?!.*not).*$

配對結果

開頭不是某個字元

  1. 開頭不是 my

    ^(?!my)\w+$

  1. 開頭不是 1/3/5

    ^(?!.[135]).$

比對 src=" ... " 符合相對路徑的 path

$reg = '(src=["|\'](?!.*(http[s]?))(?!.*(www\.))[\/]?(([^\s\[\\"\'])+)["|\'])';

match連結並且顯示頭4個字元

改成:

$message = 'google : www.google.com.tw ,yahoo : http://www.google.com.tw';
$message = preg_replace_callback(
    "/(((http[s]?):\/\/|www\.)([^\s\[\\\"'])+)/",
    function ($matches) {
        if (substr(strtolower($matches[0]), 0, 4) == 'www.')
        {
            return '<a href="http://'. $matches[0] .'" target="_blank">'. $matches[0] .'</a>';
        }
        return '<a href="'. $matches[0] .'" target="_blank">'. $matches[0] .'</a>';
    },
    $message
);
return $message;

得到預期的結果:

google : www. ,yahoo : http