OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In Dart

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In Dart with sample and detail explanation

Dart language has a wealth of robust features that makes string manipulation effortless. One common requirement that developers often meet is checking if a string contains only alphanumeric characters.

Code Snippet: Check If A String Contains Only Alphanumeric Characters In Dart

To determine if a string holds only alphanumeric characters in Dart, we’ll use the Regex method. Here’s a concise snippet of code that accomplishes this goal:

bool isAlphanumeric(String s) {
  return RegExp(r'^[a-zA-Z0-9]+$').hasMatch(s);
}

With this code in place, you will receive a boolean value telling you whether your string follows the alphanumeric rule.

Code Explanation: Check If A String Contains Only Alphanumeric Characters In Dart

Let’s break it down:

  1. We’ve created a function isAlphanumeric() which accepts a string ‘s’ as a parameter.

  2. Inside the function, we’ll utilize Dart’s RegExp class, which enables us to create and use Regular Expressions.

  3. The '^[a-zA-Z0-9]+$' is the regular expression used as a pattern to check if every character in the string falls within the alphanumeric range,a-z, A-Z or 0-9.

  4. '^' denotes the start of the line while the $ symbolizes the end of the line.

  5. The ’+’ sign allows for one or more occurrences of the preceding element which in this case, is a character from a-z, A-Z or 0-9.

  6. hasMatch(s) method is utilized to check if the expression pattern matches the string ‘s’. If it does, it will return true and if it doesn’t, it will return false.

With that, you can now easily check if a string contains only alphanumeric characters in Dart by calling the function isAlphanumeric().

dart