match()

优质
小牛编辑
117浏览
2023-12-01

描述 (Description)

此方法用于在将字符串与正则表达式匹配时检索匹配项。 它与没有g标志的regexp.exec(string)类似,它返回一个与g标志匹配的数组。

语法 (Syntax)

下面给出了JavaScript的match()方法的语法。 我们可以在CoffeeScript代码中使用相同的方法。

string.match( param )

例子 (Example)

以下示例演示了CoffeeScript代码中JavaScript的match()方法的用法。 将此代码保存在名为string_localecompare.coffee的文件中

str = "For more information, see Chapter 3.4.5.1";
re = /(chapter \d+(\.\d)*)/i;
found = str.match re
console.log found 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c coffee string_match.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var found, re, str;
  str = "For more information, see Chapter 3.4.5.1";
  re = /(chapter \d+(\.\d)*)/i;
  found = str.match(re);
  console.log(found);
}).call(this);

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee string_match.coffee 

执行时,CoffeeScript文件生成以下输出。

[ 'Chapter 3.4.5.1',
  'Chapter 3.4.5.1',
  '.1',
  index: 26,
  input: 'For more information, see Chapter 3.4.5.1' ]