📌  相关文章
📜  Dart 正则表达式所有匹配 - Javascript (1)

📅  最后修改于: 2023-12-03 15:14:36.561000             🧑  作者: Mango

Dart 正则表达式所有匹配 - Javascript

Dart 正则表达式是一种强大的工具,它可以匹配字符串中的任何模式。在 Dart 中,我们可以使用 RegExp 类来创建和操作正则表达式。下面是一个简单的例子:

RegExp regExp = new RegExp(r'hello');
String str = "hello, world!";
Iterable<Match> matches = regExp.allMatches(str);
for (Match match in matches) {
  print('${match.start} - ${match.end}: ${match.group(0)}');
}

以上代码将会输出:

0 - 5: hello

这是因为“hello”正好在字符串“hello, world!”的开头匹配。

接下来我们看一下如何用 Dart 正则表达式匹配多个字符串。同样,我们可以使用 allMatches() 方法来实现。下面是一个示例:

RegExp regExp = new RegExp(r'world');
String str = "hello, world! world!";
Iterable<Match> matches = regExp.allMatches(str);
for (Match match in matches) {
  print('${match.start} - ${match.end}: ${match.group(0)}');
}

以上代码将会输出:

7 - 12: world
14 - 19: world

这是因为“world”在字符串“hello, world! world!”中出现两次。

接下来我们来看一下如何用正则表达式匹配一个范围内的数字。例如,我们想要匹配在 0 和 999 之间的数字,可以使用下面的正则表达式:

RegExp regExp = new RegExp(r'\b([1-9]|[1-9]\d{1,2}|[1-8]\d{3}|9[0-8]\d|99[0-9])\b');
String str = "1 12 123 1234 9999";
Iterable<Match> matches = regExp.allMatches(str);
for (Match match in matches) {
  print('${match.start} - ${match.end}: ${match.group(0)}');
}

以上代码将会输出:

0 - 1: 1
2 - 4: 12
5 - 8: 123

正则表达式 \b([1-9]|[1-9]\d{1,2}|[1-8]\d{3}|9[0-8]\d|99[0-9])\b 可以解释为:

  • \b: 匹配单词边界
  • ([1-9]|[1-9]\d{1,2}|[1-8]\d{3}|9[0-8]\d|99[0-9]): 匹配数字,可以是 1 至 999,或者 1000 至 99999,或者是 100000 至 99999999

以上就是 Dart 正则表达式所有匹配的介绍。Dart 提供了丰富的正则表达式匹配功能,可以帮助我们更方便地处理字符串。