搜索插件、代码仓与 APP 分类

插件详情v2.4.0

text_parser

一个用于根据多个正则表达式模式灵活解析文本为易于处理格式的 Dart 包。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
1380
喜欢数
8
Pub 分数
160

安装插件

flutter pub add text_parser

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

一个 Dart 包,旨在通过应用多个正则表达式模式灵活解析文本,将复杂文本转换为结构化、易于处理的格式。它使开发者能够定义自定义解析规则,并高效提取有意义的数据。非常适合处理具有统一模式的日志、配置文件或用户输入。该包支持所有主要平台,确保跨平台兼容性。其轻量级设计和清晰的 API 使其适用于简单和高级的文本操作任务。

适合场景

  • 解析日志文件
  • 从用户输入中提取结构化数据
  • 处理配置字符串
  • 处理动态文本模板
  • 将原始文本转换为类似 JSON 的结构

主要特点

  • 支持多个正则表达式模式
  • 灵活且可扩展的解析逻辑
  • 跨平台兼容性
  • 用于定义规则的简单 API
  • 高效的文本转换
  • 内置错误处理

适合对象

  • 使用结构化文本的开发者
  • 需要动态文本处理的应用程序
  • 用于分析或从文本中提取数据的工具
  • 跨平台应用程序
  • 需要自定义解析工作流的项目

使用建议

  • 需要了解正则表达式
  • 性能可能因复杂模式而异
  • 未针对非常大的文本文件进行优化
  • 有限的内置格式化选项
  • 依赖于正确的模式定义以获得准确的结果

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Pub Version Dart CI codecov

A Dart package for parsing text flexibly according to preset or custom regular expression patterns.

Usage

Using the preset matchers (URL / email address / phone number)

The package has the following preset matchers.

Below is an example of using three of the preset matchers except for UrlLikeMatcher.

import 'package:text_parser/text_parser.dart';

void main() {
  const text = 'abc https://example.com/sample.jpg. def\n'
      'john.doe@example.com +1-012-3456-7890';

  final parser = TextParser(
    matchers: const [
      EmailMatcher(),
      UrlMatcher(),
      TelMatcher(),
    ],
  );
  final elements = parser.parseSync(text);
  elements.forEach(print);
}

Output:

TextElement(matcherType: TextMatcher, matcherIndex null, offset: 0, text: abc , groups: [])
TextElement(matcherType: UrlMatcher, matcherIndex 1, offset: 4, text: https://example.com/sample.jpg, groups: [])
TextElement(matcherType: TextMatcher, matcherIndex null, offset: 34, text: . def\n, groups: [])
TextElement(matcherType: EmailMatcher, matcherIndex 0, offset: 40, text: john.doe@example.com, groups: [])
TextElement(matcherType: TextMatcher, matcherIndex null, offset: 60, text:  , groups: [])
TextElement(matcherType: TelMatcher, matcherIndex 2, offset: 61, text: +1-012-3456-7890, groups: [])

The regular expression pattern of each of them is not very strict. If it does not meet your use case, overwrite the pattern by yourself to make it stricter.

parse() vs parseSync()

parseSync() literally executes parsing synchronously. If you want to prevent an execution from blocking the UI in Flutter or pauses other tasks in pure Dart, use parse() instead.

  • useIsolate: false
    • Parsing is scheduled as a microtask.
  • useIsolate: true (default)
    • Parsing is executed in an isolate.
    • On Flutter Web, this is treated the same as useIsolate: false since dart:isolate is not supported on the platform.
UrlMatcher vs UrlLikeMatcher

UrlMatcher does not match URLs not starting with "http" (e.g. example.com, //example.com, etc). If you want them to be matched too, use UrlLikeMatcher instead.

matcherType and matcherIndex

matcherType contained in a TextElement object is the type of the matcher that was used to extract the element. matcherIndex is the index of the matcher in the matcher list passed to the matchers argument of TextParser.

Extracting only matching text elements

By default, the result of parse() or parseSync() contains all elements including the ones that have TextMatcher as matcherType, which are elements of a string that did not match any match pattern. If you want to exclude them, pass onlyMatches: true when calling parse() or parseSync().

final elements = parser.parseSync(text, onlyMatches: true);
elements.forEach(print);

Output:

TextElement(matcherType: UrlMatcher, matcherIndex 1, offset: 4, text: https://example.com/sample.jpg, groups: [])
TextElement(matcherType: EmailMatcher, matcherIndex 0, offset: 40, text: foo@example.com, groups: [])
TextElement(matcherType: TelMatcher, matcherIndex 2, offset: 56, text: +1-012-3456-7890, groups: [])
Extracting text elements of a particular matcher type
final telElements = elements.whereMatcherType<TelMatcher>().toList();

Or use a classic way:

final telElements = elements.map((elm) => elm.matcherType == TelMatcher).toList();
Conflict between matchers

If multiple matchers match the string at the same position in text, the first one in those matchers takes precedence.

final parser = TextParser(matchers: const[UrlLikeMatcher(), EmailMatcher()]);
final elements = parser.parseSync('foo.bar@example.com');

In this example, UrlLikeMatcher matches foo.bar and EmailMatcher matches foo.bar@example.com, but UrlLikeMatcher is used because it is written before EmailMatcher in the matchers list.

Overwriting the pattern of a preset matcher

If you want to parse a sequence of eleven numbers after "tel:" as a phone number:

TelMatcher(r'(?<=tel:)\d{11}')
Using a custom pattern

You can create a matcher with a custom pattern either with PatternMatcher or by extending TextMatcher.

PatternMatcher
const boldMatcher = PatternMatcher(r'\*\*(.+?)\*\*');
final parser = TextParser(matchers: [boldMatcher]);
Custom matcher class

It is also possible to create a matcher class by extending TextMatcher.

Below is an example of a matcher that parses the HTML <a> tags into a set of the href value and the link text.

class ATagMatcher extends TextMatcher {
  const ATagMatcher()
      : super(
          r'\<a\s(?:.+?\s)*?href="(.+?)".*?\>'
          r'\s*(.+?)\s*'
          r'\</a\>',
        );
}
const text = '''
<a class="foo" href="https://example.com/">
  Content inside tags
</a>
''';

final parser = TextParser(
  matchers: const [ATagMatcher()],
  dotAll: true,
);
final elements = parser.parseSync(text, onlyMatches: true);
print(elements.first.groups);

Output:

[https://example.com/, Content inside tags]
ExactMatcher

ExactMatcher escapes reserved characters of RegExp so that those are used as regular characters. The parser extracts the substrings that exactly match any of the strings in the list passed as the argument.

TextParser(
  matchers: [
    // 'e.g.' matches only 'e.g.', not 'edge' nor 'eggs'.
    ExactMatcher(['e.g.', 'i.e.']),
  ],
)
Groups

Each TextElement in a parse result has the property of groups. It is a list of strings that have matched the smaller pattern inside every set of parentheses ( ).

Below is an example of a pattern that matches a Markdown style link.

r'\[(.+?)\]\((.*?)\)'

This pattern has two sets of parentheses; (.+?) in \[(.+?)\] and (/*?) in \((.*?)\). When this matches [foo](bar), the first set of parentheses captures "foo" and the second set captures "bar", so groups results in ['foo', 'bar'].

Tip:

If you want certain parentheses to be not captured as a group, add ?: after the opening parenthesis, like (?:pattern) instead of (pattern).

Named groups

Named groups are captured too, but their names are lost in the resulting groups list. Below is an example where a single match pattern contains capturing of both unnamed and named groups.

final parser = TextParser(
  matchers: const [PatternMatcher(r'(?<year>\d{4})-(\d{2})-(?<day>\d{2})')],
);
final elements = parser.parseSync('2020-01-23');
print(elements.first);

Output:

TextElement(matcherType: PatternMatcher, matcherIndex 0, offset: 0, text: 2020-01-23, groups: [2020, 01, 23])
RegExp options

How a regular expression is treated can be configured in the TextParser constructor.

  • multiLine
  • caseSensitive
  • unicode
  • dotAll

These options are passed to the constructor of RegExp internally, so refer to its document for information.

所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目