0

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.

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0
String find(String str) {
RegExp exp = RegExp(r'==([^]*?)==');
RegExpMatch? match = exp.firstMatch(str);
return match?.group(1) ?? '';

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.