0

I am trying to convert a Java regex to a Flutter(Dart) regex but I am having trouble.

My Java Code and Regex example, witch returns Matching:

    public static void main(String[] args) {
    String EMAIL_VALIDATION_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    String email = "[email protected]";
    if(!Pattern.matches(EMAIL_VALIDATION_REGEX, email)) {
        System.out.println("Not matching!");
    }else {
        System.out.println("Matching!");
    }
}

My Flutter Code example witch returns Not Matching:

    final RegExp _emailRegex = RegExp(
    r"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$",
    caseSensitive: false,
    multiLine: false);

final String _email = "[email protected]";

if (!_emailRegex.hasMatch(_email)) {
  print("Not Matching!");
} else {
  print("Matching!");
}

I have basically copied the regex that i use in java and added r as a prefix. Can someone help me identify the issue with this code?

1 Answer 1

1

The r prefix creates a raw String. As a result you don't need to double escape your \\. sequence. Use a single backslash: \.

See https://api.flutter.dev/flutter/dart-core/RegExp-class.html

Note the use of a raw string (a string prefixed with r) in the example above. Use a raw string to treat each character in a string as a literal character.

And https://www.learndartprogramming.com/fundamentals/strings-and-raw-strings-in-dart/

What is a raw strings in Dart: In Dart programming language, raw strings are a type of strings where special characters such as \ do not get special treatment.

Raw strings are useful when you want to define a String that has a lot of special characters.

Raw strings are also useful when you are defining complex regular expressions that otherwise are difficlut to define using the single and double quotes.

The main advantage of using a raw String with regular expressions is that, unlike in Java, you can copy and paste your regex and test it easily in other tools, such as https://www.regexr.com, without worrying about additional escaping.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.