Skip to content

7. 正则表达式

Image

7.1. 脚本 [regex-01]

在 PHP 课程中,我们使用以下代码来演示 PHP 7 的正则表达式:


<?php
 
// strict type for function parameters
declare (strict_types=1);
 
// regular expressions in php
// retrieve the various fields of a string
// the model: a sequence of numbers surrounded by any characters
// you only want to retrieve the sequence of digits
$modèle = "/(\d+)/";
// the chain is compared with the
compareModele2Chaine($modèle, "xyz1234abcd");
compareModele2Chaine($modèle, "12 34");
compareModele2Chaine($modèle, "abcd");
 
// the model: a sequence of numbers surrounded by any characters
// we want the sequence of numbers and the fields that follow and precede them
$modèle = "/^(.*?)(\d+)(.*?)$/";
// the chain is compared with the model
compareModele2Chaine($modèle, "xyz1234abcd");
compareModele2Chaine($modèle, "12 34");
compareModele2Chaine($modèle, "abcd");
 
// the template - a date in dd/mm/yy format
$modèle = "/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/";
compareModele2Chaine($modèle, "10/05/97");
compareModele2Chaine($modèle, "  04/04/01  ");
compareModele2Chaine($modèle, "5/1/01");
 
// the model - a decimal number
$modèle = "/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/";
compareModele2Chaine($modèle, "187.8");
compareModele2Chaine($modèle, "-0.6");
compareModele2Chaine($modèle, "4");
compareModele2Chaine($modèle, ".6");
compareModele2Chaine($modèle, "4.");
compareModele2Chaine($modèle, " + 4");
 
// end
exit;
 
// --------------------------------------------------------------------------
function compareModele2Chaine(string $modèle, string $chaîne): void {
  // compares the $chaîne string with the $modèle model
  // the chain is compared with the model
  $champs = [];
  $correspond = preg_match($modèle, $chaîne, $champs);
  // displaying results
  print "\nRésultats($modèle,$chaîne)\n";
  if ($correspond) {
    for ($i = 0; $i < count($champs); $i++) {
      print "champs[$i]=$champs[$i]\n";
    }
  } else {
    print "La chaîne [$chaîne] ne correspond pas au modèle [$modèle]\n";
  }
}

我们将此代码转换为 JavaScript 如下:


'use strict';
 
/// regular expressions in javascript
// retrieve the various fields of a string
// the model: a sequence of numbers surrounded by any characters
// you only want to retrieve the sequence of digits
let modèle = /(\d+)/;
// the chain is compared with the
compareModèleToChaîne(modèle, "xyz1234abcd");
compareModèleToChaîne(modèle, "12 34");
compareModèleToChaîne(modèle, "abcd");
 
// the model: a sequence of numbers surrounded by any characters
// we want the sequence of numbers and the fields that follow and precede them
modèle = /^(.*?)(\d+)(.*?)$/;
// the chain is compared with the
compareModèleToChaîne(modèle, "xyz1234abcd");
compareModèleToChaîne(modèle, "12 34");
compareModèleToChaîne(modèle, "abcd");
 
// the template - a date in dd/mm/yy format
modèle = /^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/;
compareModèleToChaîne(modèle, "10/05/97");
compareModèleToChaîne(modèle, "  04/04/01  ");
compareModèleToChaîne(modèle, "5/1/01");
 
// the model - a decimal number
modèle = /^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/;
compareModèleToChaîne(modèle, "187.8");
compareModèleToChaîne(modèle, "-0.6");
compareModèleToChaîne(modèle, "4");
compareModèleToChaîne(modèle, ".6");
compareModèleToChaîne(modèle, "4.");
compareModèleToChaîne(modèle, " + 4");
 
// --------------------------------------------------------------------------
function compareModèleToChaîne(modèle, chaîne) {
  // compares the string [string] with the model [model]
  console.log(`----------- chaîne=${chaîne}, modèle=${modèle}`)
  // the chain is compared with the
  const result1 = modèle.exec(chaîne);
  console.log(`comparaison avec exec=`, result1);
  // another way of doing things
  const result2 = chaîne.match(modèle);
  console.log(`comparaison avec match=`, result2);
}

注释

  • PHP 和 JavaScript 代码非常相似;
  • 第 7 行:请注意,在 JavaScript 中,正则表达式不是字符串,而是一个对象。请勿在表达式周围添加引号或撇号;
  • 第 41 行和第 44 行:有两种方法可以实现相同的结果;

执行


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\regexp\regexp-01.js"
type d'une expression régulière : object
----------- chaîne=xyz1234abcd, modèle=/(\d+)/
comparaison avec exec= [ '1234',
'1234',
index: 3,
input: 'xyz1234abcd',
groups: undefined ]
comparaison avec match= [ '1234',
'1234',
index: 3,
input: 'xyz1234abcd',
groups: undefined ]
----------- chaîne=12 34, modèle=/(\d+)/
comparaison avec exec= [ '12', '12', index: 0, input: '12 34', groups: undefined ]
comparaison avec match= [ '12', '12', index: 0, input: '12 34', groups: undefined ]
----------- chaîne=abcd, modèle=/(\d+)/
comparaison avec exec= null
comparaison avec match= null
----------- chaîne=xyz1234abcd, modèle=/^(.*?)(\d+)(.*?)$/
comparaison avec exec= [ 'xyz1234abcd',
'xyz',
'1234',
'abcd',
index: 0,
input: 'xyz1234abcd',
groups: undefined ]
comparaison avec match= [ 'xyz1234abcd',
'xyz',
'1234',
'abcd',
index: 0,
input: 'xyz1234abcd',
groups: undefined ]
----------- chaîne=12 34, modèle=/^(.*?)(\d+)(.*?)$/
comparaison avec exec= [ '12 34',
'',
'12',
' 34',
index: 0,
input: '12 34',
groups: undefined ]
comparaison avec match= [ '12 34',
'',
'12',
' 34',
index: 0,
input: '12 34',
groups: undefined ]
----------- chaîne=abcd, modèle=/^(.*?)(\d+)(.*?)$/
comparaison avec exec= null
comparaison avec match= null
----------- chaîne=10/05/97, modèle=/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/
comparaison avec exec= [ '10/05/97',
'10',
'05',
'97',
index: 0,
input: '10/05/97',
groups: undefined ]
comparaison avec match= [ '10/05/97',
'10',
'05',
'97',
index: 0,
input: '10/05/97',
groups: undefined ]
----------- chaîne= 04/04/01 , modèle=/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/
comparaison avec exec= [ ' 04/04/01 ',
'04',
'04',
'01',
index: 0,
input: ' 04/04/01 ',
groups: undefined ]
comparaison avec match= [ ' 04/04/01 ',
'04',
'04',
'01',
index: 0,
input: ' 04/04/01 ',
groups: undefined ]
----------- chaîne=5/1/01, modèle=/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/
comparaison avec exec= null
comparaison avec match= null
----------- chaîne=187.8, modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ '187.8',
'',
'187.8',
index: 0,
input: '187.8',
groups: undefined ]
comparaison avec match= [ '187.8',
'',
'187.8',
index: 0,
input: '187.8',
groups: undefined ]
----------- chaîne=-0.6, modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ '-0.6', '-', '0.6', index: 0, input: '-0.6', groups: undefined ]
comparaison avec match= [ '-0.6', '-', '0.6', index: 0, input: '-0.6', groups: undefined ]
----------- chaîne=4, modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ '4', '', '4', index: 0, input: '4', groups: undefined ]
comparaison avec match= [ '4', '', '4', index: 0, input: '4', groups: undefined ]
----------- chaîne=.6, modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ '.6', '', '.6', index: 0, input: '.6', groups: undefined ]
comparaison avec match= [ '.6', '', '.6', index: 0, input: '.6', groups: undefined ]
----------- chaîne=4., modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ '4.', '', '4.', index: 0, input: '4.', groups: undefined ]
comparaison avec match= [ '4.', '', '4.', index: 0, input: '4.', groups: undefined ]
----------- chaîne= + 4, modèle=/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$/
comparaison avec exec= [ ' + 4', '+', '4', index: 0, input: ' + 4', groups: undefined ]
comparaison avec match= [ ' + 4', '+', '4', index: 0, input: ' + 4', groups: undefined ]

[regexp.exec][string.match] 方法返回相同的结果:

  • [null],如果字符串与正则表达式模式之间没有匹配;
  • 若存在匹配,则返回数组 t,其中:
    • t[0]:与模式匹配的字符串;
    • t[1]:与模式中第一个括号匹配的字符串;
    • t[2]:与模式中第二个括号匹配的字符串;
    • t[input]:包含该模式的整个字符串;

7.2. 脚本 [regexp-02]

有时你并不想从被测试的字符串中提取元素,而只想知道它是否与模式匹配:


'use strict';
 
/// regular expressions in javascript
// retrieve the various fields of a string
// the model: a sequence of numbers surrounded by any characters
// you only want to retrieve the sequence of digits
let modèle = /\d+/;
console.log("type d'une expression régulière : ", typeof (modèle));
// the chain is compared with the
compareModèleToChaîne(modèle, "xyz1234abcd");
compareModèleToChaîne(modèle, "12 34");
compareModèleToChaîne(modèle, "abcd");
 
// the model: a sequence of numbers surrounded by any characters
// we want the sequence of numbers and the fields that follow and precede them
modèle = /^.*?\d+.*?$/;
// the chain is compared with the
compareModèleToChaîne(modèle, "xyz1234abcd");
compareModèleToChaîne(modèle, "12 34");
compareModèleToChaîne(modèle, "abcd");
 
// the template - a date in dd/mm/yy format
modèle = /^\s*\d\d\/\d\d\/\d\d\s*$/;
compareModèleToChaîne(modèle, "10/05/97");
compareModèleToChaîne(modèle, "  04/04/01  ");
compareModèleToChaîne(modèle, "5/1/01");
 
// the model - a decimal number
modèle = /^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/;
compareModèleToChaîne(modèle, "187.8");
compareModèleToChaîne(modèle, "-0.6");
compareModèleToChaîne(modèle, "4");
compareModèleToChaîne(modèle, ".6");
compareModèleToChaîne(modèle, "4.");
compareModèleToChaîne(modèle, " + 4");
 
// --------------------------------------------------------------------------
function compareModèleToChaîne(modèle, chaîne) {
  // test
  const correspond = modèle.test(chaîne);
  // compares the string [string] with the model [model]
  console.log(`----------- chaîne=${chaîne}, modèle=${modèle}, correspond=${correspond}`);
}

注释

  • [regexp-02] 使用了 [regexp-01] 中的代码,但有以下区别:
    • 我们不希望从待测试的字符串中提取元素。因此,我们移除了所用正则表达式中的括号;
    • 第 40 行:我们使用 [Regexp.test] 方法来判断字符串是否与正则表达式匹配;

执行结果如下:


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\cours\regexp\regexp-02.js"
type d'une expression régulière :  object
----------- chaîne=xyz1234abcd, modèle=/\d+/, correspond=true
----------- chaîne=12 34, modèle=/\d+/, correspond=true
----------- chaîne=abcd, modèle=/\d+/, correspond=false
----------- chaîne=xyz1234abcd, modèle=/^.*?\d+.*?$/, correspond=true
----------- chaîne=12 34, modèle=/^.*?\d+.*?$/, correspond=true
----------- chaîne=abcd, modèle=/^.*?\d+.*?$/, correspond=false
----------- chaîne=10/05/97, modèle=/^\s*\d\d\/\d\d\/\d\d\s*$/, correspond=true
----------- chaîne=  04/04/01  , modèle=/^\s*\d\d\/\d\d\/\d\d\s*$/, correspond=true
----------- chaîne=5/1/01, modèle=/^\s*\d\d\/\d\d\/\d\d\s*$/, correspond=false
----------- chaîne=187.8, modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
----------- chaîne=-0.6, modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
----------- chaîne=4, modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
----------- chaîne=.6, modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
----------- chaîne=4., modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
----------- chaîne= + 4, modèle=/^\s*[+|-]?\s*\d+\.\d*|\.\d+|\d+\s*$/, correspond=true
 
[Done] exited with code=0 in 0.269 seconds