Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you tried to include options in the raw expression string while you already have it as parameters to RegEx ( /i for case insensitivity is declared as 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());

Gives:

allMatches : (Instance of '_MatchImplementation')
firstMatch : Instance of '_MatchImplementation'
hasMatch : true
stringMatch : WS://127.0.0.1:56789

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...