Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, get entire string between two keywords

Tags:

c++

regex

I'm doing some output parsing where I need to grab a chunk of text from inbetween two words. For instance if I'm parsing the text

"Hi this is an example"

I want to be able to specify that my two words are "Hi" and "example", and i will get back the string

" this is an "

I know that regular expressions are useful but I'm unfamiliar with them. Any ideas?

like image 964
Nate Rubin Avatar asked Oct 23 '25 18:10

Nate Rubin


2 Answers

You're going to want a regex that looks like

Hi(.*?)example

We want to capture everything in ()s

. matches any character

* means we want from 0 to infinity .

We add a ? at the end so that we match non-greedily otherwise it would gobble up everything until the last "example" in your text, rather that the first "example" after "Hi".

EDIT: As far as regex testers go, I like Rubular. It's techincally ruby specific but works fine for simple things. It shows whole regex matches and the capture groups. Here's your example: http://rubular.com/r/c9I4cmJqBx

like image 188
axblount Avatar answered Oct 26 '25 06:10

axblount


This regex will match everything between the two words:

(?<=Hi).*(?=example)

This regex employs "look arounds" which obviates the need for capturing a group and then extractingg it - the entire match is your target.

like image 43
Bohemian Avatar answered Oct 26 '25 07:10

Bohemian