Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RegEx in Dart?

In a Flutter application, I need to check if a string matches a specific RegEx. However, the RegEx I copied from the JavaScript version of the app always returns false in the Flutter app. I verified on regexr that the RegEx is valid, and this very RegEx is already being used in the JavaScript application, so it should be correct.

Any help is appreciated!

RegEx : /^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i

Test Code :

RegExp regExp = new RegExp(   r"/^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i",   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()); 

Output :

allMatches : () firstMatch : null hasMatch : false stringMatch : null 
like image 203
Nato Boram Avatar asked Apr 10 '18 15:04

Nato Boram


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do I match a pattern in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

This is a more general answer for future viewers.

Regex in Dart works much like other languages. You use the RegExp class to define a matching pattern. Then use hasMatch() to test the pattern on a string.

Examples

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 

Extracting text

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 

There are some more examples here.

See also:

  • Extracting text from a string with regex groups in Dart
like image 57
Suragch Avatar answered Sep 28 '22 15:09

Suragch