简体   繁体   中英

Java Regex to Flutter Regex

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 = "testemail@gmail.com";
    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 = "testemail@gmail.com";

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM