Home > Net >  Flutter - I want to know how to extract certain sentences from long characters into regex
Flutter - I want to know how to extract certain sentences from long characters into regex

Time:08-05

I want to extract the sentence I want from the long sentence. Also, I want to know how to use regular expressions.

For example,

sdlkfjklsdjf lds \@test text@\ slkdjflksdjf

I want to extract "test text", a sentence that starts with \@ and ends with @\ in the above sentence.

I tried to use lookahead and lookbehind, but I failed. Is there a way to solve the problem?

CodePudding user response:

Dart doesn't support look behinds.

Instead, capture your target in a group:

final innerString = RegExp(r'\\@(.*)@\\').firstMatch(str)?.group(1);

Runnable code:

void main() {
  final str = "sdlkfjklsdjf lds \\@test text@\\ slkdjflksdjf";
  final innerString = RegExp(r'\\@(.*)@\\').firstMatch(str)?.group(1);
  print(innerString);
}

Output:

test text

CodePudding user response:

You can try this

String str = "sdlkfjklsdjf lds \@test text@\ slkdjflksdjf";
final startIndex = str.indexOf("\@");
  final endIndex = str.indexOf("@\", startIndex   "/@".length);

  print(str.substring(startIndex   "/@".length, endIndex)); 
}
  • Related