RegEx działa z kotlin, ale nie działa zgodnie z oczekiwaniami z dartem [duplikat]

Dec 07 2020

Wyrażenie regularne działa dobrze w kodzie kotlin:

var text = "Today, scientists confirmed the worst possible outcome: the massive asteroid will collide with Earth"
    
val encodeRegex = Regex("""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
    
   val x= encodeRegex.findAll(text).map { result ->
            result.value
        }
     
    print(x.toList())

Wyjście:

    [Today, ,,  scientists,  confirmed,  the,  worst,  possible,  outcome, :,  the,  massive,  asteroid,  will,  collide,  with,  Earth]

Próbowałem użyć tego samego wyrażenia regularnego z flutter, ale nie działa zgodnie z oczekiwaniami.

Kod do darta:

    final RegExp encodeRegex = RegExp(
    r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""",
  );
  
  final text ='Today, scientists confirmed the worst possible outcome: the massive asteroid will collide with Earth';
  
  
  final tokens = encodeRegex
        .allMatches(text)
        .map(
          (element) =>
              element.group(0),
        )
        .toList();
  
  print('${tokens}');

Wyjście:

[Today,,  scientists,  confirmed,  the,  worst,  , ossible,  outcome:,  the,  massive,  asteroid,  will,  collide,  with,  Earth]

Odpowiedzi

Iliya Dec 07 2020 at 02:53

Problem polega na tym, że domyślnie wyrażenie regularne nie pasuje do kategorii Unicode. Musisz dodać, unicode: trueaby wyrażenie regularne do nich pasowało. Próbować:

    main(){
final RegExp encodeRegex = RegExp(
    r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""", unicode: true
  );
  
final text ='Today, scientists confirmed the worst possible outcome: the massive asteroid will collide with Earth';
  
  
final tokens = encodeRegex
        .allMatches(text)
        .map(
          (element) =>
              element.group(0),
        )
        .toList();
  
  print('${tokens}');
}

Działa w DartPad. Jeśli unicode nie jest włączony, pasuje p{L}i p{N}jako dosłowne pL i pN.