1

What would be the shortest solution to capture a string between two markers?

For example, let's imagine I have

blahblahblah ---foobar-- blahblahblah

And I want to capture "foobar".

I can capture the string "---foobar--" quite easily with a regex.

But since I don't want the prefix "---" and suffix "--", I need many steps to clean up the result :

  1. get position of prefix "---" (since we already captured the bloc, we know the position is 0)
  2. get length of "---" (for the sake of the example, let's assume we don't know the size of the limiter, it can be "---" or "--" or "-")
  3. get position of suffix "--", starting at position position_prefix+prefix_length
  4. substring between position_prefix+prefix_length and position_suffix

Of course I can build myself such a function to do that if I need it, but is there already a built-in solution for that?

Something like captureWithoutDelimiters(group_regex, prefix_regex, suffix_regex) ?

0

2 Answers 2

3

How about:

[\w\s]+-+(\w+)-+[\w\s]+

Then you can just print out what's caught by the first capture group.

Explanation:

[\w\s]+     // Match at lest 1 letter or white space character
-+          // Followed by at least 1 marker character
(\w+)       // Capture the word inside the markers
-+          // Followed by more marker characters
[\w\s]+     // Followed by at lest 1 letter/white space character
1
  • I didn't know about capture groups, seems like the ideal tool for the job!
    – Mikarnage
    Nov 8, 2012 at 14:05
1

The shortest solution probably would be

.split("-+")[1]

If you require --- as prefix and -- as postfix and you allow - anywhere in text, then split solution is

.split("---")[1].split("--")[0]

See this demo.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.