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
)
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.
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.
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.
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** "
Using the same regex given by Victor, you can also do
var.split(/container_start(.*?)container_end/)[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With