RegExはkotlinで動作しますが、dartでは期待どおりに動作しませんでした[重複]

Dec 07 2020

正規表現は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())

出力:

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

同じ正規表現をフラッターで使用しようとしましたが、期待どおりに機能しません。

ダーツコード:

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

出力:

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

回答

Iliya Dec 07 2020 at 02:53

問題は、デフォルトで正規表現がUnicodeカテゴリと一致しないことです。unicode: true正規表現をそれらに一致させるには、を追加する必要があります。試してみてください:

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

DartPadで動作します。Unicodeが有効になっていない場合は、リテラルpLおよびpNとして一致p{L}p{N}ます。