I have string like this one ==here==
. How can I get here
using RegEx pattern.
I know I can use .substring
like
const pattern = "==";
const str = "==here==";
final start = str.indexOf(pattern) pattern.length;
final end = str.lastIndexOf(pattern);
final sub = str.substring(start, end);
expect(sub, 'here');
for this but I want to use regex pattern so that I could get first match correctly.
What I want exactly is to get first string that is wrapped in two ==
even if there are thousand matches.
CodePudding user response:
The simplest RegExp just matches ==(something)==
and uses the capture.
Here it uses a non-greedy match so that it finds the first following ==
.
var re = RegExp(r'==([^]*?)==');
var sub = re.firstMatch(str)?[1];
If you need the RegExp match itself to be the string between the ==
s, you can use look-behind and look-ahead:
var re = RegExp(r'(?<===)[^]*?(?===)');
var sub = re.firstMatch(str)?[0];
CodePudding user response:
String find(String str) {
RegExp exp = RegExp(r'==([^]*?)==');
RegExpMatch? match = exp.firstMatch(str);
return match?.group(1) ?? '';
}