Orientação gerada a partir de informações públicas. Apenas para referência.
Um pacote Dart projetado para analisar texto de forma flexível aplicando múltiplos padrões de expressão regular, transformando textos complexos em formatos estruturados e fáceis de manipular. Permite que desenvolvedores definam regras personalizadas de análise e extraiam dados significativos de forma eficiente. Ideal para processar logs, arquivos de configuração ou entradas de usuário com padrões consistentes. O pacote suporta todas as principais plataformas, garantindo compatibilidade entre plataformas. Seu design leve e sua API clara o tornam adequado tanto para tarefas simples quanto avançadas de manipulação de texto.
Casos de uso
Analisando arquivos de log
Extraindo dados estruturados da entrada do usuário
Processando strings de configuração
Manipulação de modelos de texto dinâmicos
Transformando texto bruto em estruturas semelhantes a JSON
Principais recursos
Suporta múltiplos padrões de expressão regular
Lógica de análise flexível e extensível
Compatibilidade multiplataforma
API simples para definir regras
Transformação de texto eficiente
Tratamento de erro embutido
Indicado para
Desenvolvedores trabalhando com texto estruturado
Aplicativos que exigem processamento dinâmico de texto
Ferramentas que analisam ou extraem dados de texto
Aplicações multiplataforma
Projetos que precisam de fluxos de trabalho personalizáveis de análise
Considerações
Requer conhecimento de expressões regulares
O desempenho pode variar com padrões complexos
Não otimizado para arquivos de texto muito grandes
Opções limitadas de formatação embutidas
Depende da definição correta do padrão para resultados precisos
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
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 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.
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);
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.
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);