Flutterアプリケーションでは、文字列が特定の正規表現に一致するかどうかを確認する必要があります。しかし、アプリのJavaScriptバージョンからコピーした正規表現はいつもFlutterアプリではfalseを返します。正規表現RegEx が有効であり、この RegEx がすでに JavaScript アプリケーションで使用されているため、正しいはずです。
どのような助けでも大歓迎です!
正規表現:/^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789/i
テストコード:
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());
出力:
allMatches : ()
firstMatch : null
hasMatch : false
stringMatch : null
ベストアンサー1
これは将来の視聴者向けのより一般的な回答です。
Dartの正規表現は他の言語とほぼ同じように機能します。RegExp
クラスを使用して一致するパターンを定義します。次に、hasMatch()
文字列でパターンをテストするために使用します。
例
英数字
final alphanumeric = RegExp(r'^[a-zA-Z0-9]+$');
alphanumeric.hasMatch('abc123'); // true
alphanumeric.hasMatch('abc123%'); // false
16進数カラー
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
テキストの抽出
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
他にもいくつか例がありますここ。