2017/12/18

Simple Regular Expression In PHP, Python, Node.js

今天需要用正規式找出符合 xxx[yyy] 後面任意內容的結果,紀錄一下三種語言怎麼操作正規式

PHP
<?php

$pattern = '/\w+\[\w+\].*/i';
$strings = [
    'aaa[bbb]',
    '1234[bbb][cccc]',
    '[111][22]',
    'dd[gg]ff',
    'aa[',
    'aaa][bbbb',
    'aaabbbccc',
];

foreach ($strings as $s) {
    var_dump($s.' is '.preg_match($pattern, $s));
}
Python
import re

pattern = r'\w+\[\w+\].*';
strings = [
    'aaa[bbb]',
    '1234[bbb][cccc]',
    '[111][22]',
    'dd[gg]ff',
    'aa[',
    'aaa][bbbb',
    'aaabbbccc'
];

for s in strings:
    print('%s is %s' % (s, True if re.match(pattern, s, re.IGNORECASE) else False))
Node.js
const pattern = /\w+\[\w+\].*/i;
const strings = [
    'aaa[bbb]',
    '1234[bbb][cccc]',
    '[111][22]',
    'dd[gg]ff',
    'aa[',
    'aaa][bbbb',
    'aaabbbccc'
];

for (v of strings) {
    console.log(v, 'is', pattern.test(v));
}

沒有留言: