Como usar RegEx no Dart?
O RegEx no Dart funciona da mesma forma que qualquer outro idioma. RegEx faz parte da biblioteca de código Dart, implementada na classe RegExp . Portanto, neste artigo, veremos como usar o RegEx no Dart.
Como usar RegEx no Dart?
Precisamos tentar incluir opções na string de expressão bruta enquanto você já a possui como parâmetros para RegEx ( /i para insensibilidade a maiúsculas e minúsculas é declarado como caseSensitive: false ).
// Removed /i at the end // Removed / in front - Thanks to Günter for warning RegExp regExp = new RegExp( r"^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789", caseSensitive: false, multiLine: false, ); print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString()); print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString()); print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString()); print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());
Então isso vai dar:
allMatches : (Instance of '_MatchImplementation') firstMatch : Instance of '_MatchImplementation' hasMatch : true stringMatch : WS://127.0.0.1:56789
Portanto, o Regex no dart funciona como outros idiomas. Você usa a Classe RegExp para definir um padrão de correspondência.
Agora, use hasMatch() para testar o padrão em uma string..
Exemplos para o mesmo
Alphanumeric:
final alphanumeric = RegExp(r'^[a-zA-Z0-9]+$'); alphanumeric.hasMatch('abc123'); // true alphanumeric.hasMatch('abc123%'); // false
Hex Colors:
RegExp hexColor = RegExp(r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'); hexColor.hasMatch('#3b5'); // true hexColor.hasMatch('#FF7723'); // true hexColor.hasMatch('#000000z'); // false
Então agora, extraindo o texto assim:
final myString = '25F8..25FF ; Common # Sm [8] UPPER LEFT TRIANGLE'; // find a variable length hex value at the beginning of the line final regexp = RegExp(r'^[0-9a-fA-F]+'); // find the first match though you could also do `allMatches` final match = regexp.firstMatch(myString); // group(0) is the full matched text // if your regex had groups (using parentheses) then you could get the // text from them by using group(1), group(2), etc. final matchedText = match.group(0); // 25F8
Conclusão:
Obrigado por estar conosco em uma Jornada Flutter!!! Fique ligado 🙂
Portanto, neste artigo, vimos como usar o RegEx no Dart.
Continue aprendendo !!! Continue vibrando!!!
Então, deixe-nos saber se você ainda está confuso sobre o Desenvolvimento Flutter 🙂 Nós adoraríamos ajudá-lo.