PHP/JS 经常使用的正则表达式

正则表达式的都是婚配和替代

PHP

搜刮

preg_match*

/**
 * int preg_match* ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
 * $pattern  正则表达式
 * $subject  要婚配的字符串
 * &$matches 婚配到的字符串
 * return    婚配到的个数,没有婚配到返回0
 */

下面是例子

$pattern = "/\d{2}/";
$content = "12:34:56:78:9a";
// 实行一个正则表达式婚配, 非贪欲
if (preg_match ($pattern, $content, $m)){
    print_r($m);
}

// 实行一个全局正则表达式婚配, 贪欲
if ($c = preg_match_all($pattern, $content, $m)){
    echo "match numbers is ".$c."\n";
    print_r($m);
}

实行效果

$ php run.php
Array
(
    [0] => 12
)
match numbers is 4
Array
(
    [0] => Array
        (
            [0] => 12
            [1] => 34
            [2] => 56
            [3] => 78
        )
)

preg_grep

<?php
$pattern = "/^[a-z]*$/i";
$content = ["Mechanical Engineering",
            "Medicine",
            "Social Science",
            "Agriculture",
            "Commercial Science",
            "Politics" ];
// 婚配一切仅由有一个单词构成的科目名
$alonewords = preg_grep($pattern, $content);
foreach($alonewords as $key => $value){
    echo $key.$value."\n";
}
?>

输出效果

$ php run.php
1Medicine
3Agriculture
5Politics

替代

preg_replace

/**
 * mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
 * $pattern     正则表达式
 * $subject     要婚配的字符串
 * $replacement 用于替代的字符串或字符串数组, replacement和subject的范例雷同
 * return       替代的后的对象,范例和subject雷同
 */

例子

<?php
$content  = "Name: {Name}\nEmail: {Email}\nAddress: {Address}\n";
$patterns = ["/{Name}/", "/{Email}/", "/{Address}/"];
$replace  = ["Jaime", "xsu@viewtool.com", "Chongqing China"];
echo preg_replace($patterns, $replace, $content);
?>

输出效果

$php run.php
Name: Jaime
Email: xsu@viewtool.com
Address: Chongqing China

这个相当于就是最简朴的模板完成了

php其他

PHP preg:http://php.net/manual/zh/ref.pcre.php
下面有一切的函数手册
preg_match
preg_match_all
preg_grep
preg_replace
preg_replace_callback
preg_replace_callback_array
preg_filter
grep_quote
grep_split
grep_last_error

PHP经常运用正则表达式汇总

javascript

假如是替代的正则表达式,能够本身写
假如仅仅是推断,引荐运用is.js这个库
官方网站
这里就不多引见了, 官网上的异常的清晰

    原文作者:优de良
    原文地址: https://segmentfault.com/a/1190000005700646
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞