Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: To pull out a sub-string between two tags in a string

Tags:

regex

parsing

I have a file in the following format:

 Data Data Data [Start] Data I want [End] Data 

I'd like to grab the Data I want from between the [Start] and [End] tags using a Regex. Can anyone show me how this might be done?

like image 945
Dan Avatar asked Aug 04 '08 13:08

Dan


People also ask

How do you find the string between two characters?

To get a substring between two characters:Get the index after the first occurrence of the character. Get the index of the last occurrence of the character. Use the String. slice() method to get a substring between the 2 characters.

How do you escape in RegEx?

The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.

What does RegEx (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.


2 Answers

\[start\](.*?)\[end\] 

Zhich'll put the text in the middle within a capture.

like image 76
Karl Seguin Avatar answered Oct 10 '22 03:10

Karl Seguin


\[start\]\s*(((?!\[start\]|\[end\]).)+)\s*\[end\] 

This should hopefully drop the [start] and [end] markers as well.

like image 41
Xenph Yan Avatar answered Oct 10 '22 03:10

Xenph Yan