RegEx funktioniert mit Kotlin, aber nicht wie erwartet mit Dart [Duplikat]

Dec 07 2020

Der Regex funktioniert gut im Kotlin-Code:

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())

Die Ausgabe:

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

Ich habe versucht, den gleichen regulären Ausdruck mit Flattern zu verwenden, aber es funktioniert nicht wie erwartet.

Dartcode:

    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}');

Die Ausgabe:

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

Antworten

Iliya Dec 07 2020 at 02:53

Das Problem ist, dass der reguläre Ausdruck standardmäßig nicht mit Unicode-Kategorien übereinstimmt. Sie müssen hinzufügen, unicode: truedamit der reguläre Ausdruck mit ihnen übereinstimmt. Versuchen:

    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}');
}

Es funktioniert in DartPad. Wenn Unicode nicht aktiviert ist, stimmt es mit p{L}und p{N}als Literal pL und pN überein.