1

I'm currently using this function bellow to capture text after a certain keyword in a String of text :

      static String? _getTextAfterKeyword({
    required String inputtext,
    required String keyword,
  }) {
    final indexKeyword = text.indexOf(keyword);
    final indexAfter = indexKeyword + keyword.length;

    if (indexKeyword == -1) {
      return null;
    } else {
      return text.substring(indexAfter).trim();
    }
  }

Now I'm trying to capture a String of text in between two keywords - but what I've tried hasn't worked - 🙏

To illustrate this is what I need :

inputtext = "Lorem ipsum Lorem ipsum Lorem ipsum FIRSTKEYWORD - text I would like to return - SECONDKEYWORD Lorem ipsum Lorem ipsum Lorem ipsum"

the function would look something like this :

 static String? _getTextInBetweenTwoKeywords({
    required String inputtext,
    required String firstKeyword,
    required String SecondKeyword,
  }) {

   //Some Code

      return the StringInBetweentheTwoKeywords;
    
  }
``
2
  • Can you add an example of input and output?? Commented Oct 13, 2021 at 9:27
  • Please give more detail on what you want to talk about, so that the viewers may understand better. Commented Oct 13, 2021 at 9:29

1 Answer 1

2

Would something like this do the trick?

String capture(String first, String second, String input) {
  int firstIndex = input.indexOf(first) + first.length;
  int secondIndex = input.indexOf(second);
  return input.substring(firstIndex, secondIndex);
}

void main() {
  print(capture('FIRST', 'SECOND', 'AAAAAAA FIRST-what should print-SECOND BBBBBB')); // prints '-what should print-';
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you this works! I'll try to add some code so it doesn't crash when no matching keywords are found - thank you ⚡️

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.