Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching the substring contained between two specific words

I wanted to know how to proceed when I am interested in the text contained between particular words using ruby. eg.

@var = "Hi, I want to extract container_start ONLY THIS DYNAMIC CONTENT container_end from the message contained between the container_start and container_end "

Now I want to extract the CAPITALIZED content from the string i.e. dynamic but always contained within the two containers (container_start and container_end)

like image 680
Nishutosh Sharma Avatar asked Nov 02 '12 09:11

Nishutosh Sharma


People also ask

How do I extract a string between two words in Python?

To find a string between two strings in Python, use the re.search() method. The re.search() is a built-in Python method that searches a string for a match and returns the Match object if it finds a match. If it finds more than one match, it only returns the first occurrence of the match.

How do you get a substring between two markers in Python?

Extract substring between two markers using split() method Next method that we will be using is the split() method of Python Programming language, to extract a given substring between two markers. The split() method in python splits the given string from a given separator and returns a list of splited substrings.

Which of the following function is used extract a substring between the specified range?

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. The substring() method returns the part of the string between the start and end indexes, or to the end of the string.


2 Answers

Simple regular expression would do:

@var = "Hi, I want to extract container_start **ONLY THIS DYNAMIC CONTENT** container_end from the message contained between the container_start and container_end "
@var[/container_start(.*?)container_end/, 1] # => " **ONLY THIS DYNAMIC CONTENT** "
like image 76
Victor Deryagin Avatar answered Oct 25 '22 23:10

Victor Deryagin


Using the same regex given by Victor, you can also do

var.split(/container_start(.*?)container_end/)[1]
like image 40
Dennis Avatar answered Oct 26 '22 01:10

Dennis