Home > OS >  Checking if a String container any of a set of Symbols in Dart
Checking if a String container any of a set of Symbols in Dart

Time:03-27

I would like to check if a string contains any of the following symbols ^ $ * . [ ] { } ( ) ? - " ! @ # % & / \ , > < ' : ; | _ ~ ` =

I tried using the following

string.contains(RegExp(r'[^$*.[]{}()?-"!@#%&/\,><:;_~` =]'))

But that does not seem to do anything. I am also not able to add the ' symbol.

Questions:

  1. How do I check if a string contains any one of a set of symbols?
  2. How do I add the ' symbol in my regex collection?

CodePudding user response:

When you want to check whether your String matches a RegExp pattern, you should use RegExp.hasMatch and not String.contains - String.contains searches for specific symbols in the text, not a pattern.

Also, when writing such a RegExp pattern, you should escape the special symbols (if you want to search specifically by them).

Lastly, to add the ' to the RegExp, there is no straightforward way, but you could use String concatenation to work around this.

This is what the final result could look like:

void main() {
  final regExp = RegExp(
    r'[\^$*.\[\]{}()?\-"!@#%&/\,><:;_~` =' // <-- Notice the escaped symbols
    "'" // <-- ' is added to the expression
    ']'
  );
  
  final string1 = 'abc';
  final string2 = 'abc[';
  final string3 = "'";
  
  print(regExp.hasMatch(string1)); // false
  print(regExp.hasMatch(string2)); // true
  print(regExp.hasMatch(string3)); // true
}

CodePudding user response:

To ad both ' an " to the same string literal, you can use a multiline (triple-quoted) string.

string.contains(RegExp(r'''[^$*.[\]{}()?\-"'!@#%&/\\,><:;_~` =]'''))

You also need to escape characters which have meaning inside a RegExp character class (], - and \ in particular).

Another approach is to create a set of character codes, and check if the string's characters are in that set:

var chars = r'''^$*.[]{}()?-"'!@#%&/\,><:;_~` =''';
var charSet = {...chars.codeUnits};
var containsSpecialChar = string.codeUnits.any(charSet.contains);
  •  Tags:  
  • dart
  • Related