패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.4.0

text_parser

여러 정규 표현식 패턴에 따라 텍스트를 유연하게 파싱하여 쉽게 다룰 수 있는 형식으로 변환하는 Dart 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.4천
좋아요
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 개

소스 저장소

이 패키지를 사용하는 프로젝트