Reputation: 2964
What's the best way to get the first part of a string and remove the second part in Ruby ? I know the first part to keep for each case
Examples:
"The Cuvée titi" => "The Cuvée"
"The Cuvée toto" => "The Cuvée"
"The Cuvée toto 1234" => "The Cuvée"
"1234 The Cuvée" => need to do nothing
"The wine 45 67" => "The wine"
"The wine not good" => " The wine"
"What's The wine ?" => need to do nothing
I tried many things, after reading some discussions, including:
Is a regex required ? Thanks
Upvotes: 0
Views: 120
Reputation: 110675
It appears to me that the objective could be viewed as removing the portion of the string that follows the given string.
def doit(str, given_str)
str.gsub(/(?<=\b#{given_str}\b).*/, '')
end
given_str = "The Cuvée"
doit "The Cuvée titi", given_str #=> "The Cuvée"
doit "The Cuvée toto", given_str #=> "The Cuvée"
doit "The Cuvée toto 1234", given_str #=> "The Cuvée"
doit "1234 The Cuvée", given_str #=> "1234 The Cuvée"
given_str = "The wine"
doit "The wine 45 67", given_str #=> "The wine"
doit "The wine not good", given_str #=> "The wine"
doit "What's The wine?", given_str #=> "What's The wine"
Note the question mark is removed in the last example.
For
given_str = "The wine"
the regular expression is
/(?<=\b#{given_str}\b).*/
#=> /(?<=\bThe wine\b).*/
(?<=\bThe wine\b)
is a positive lookbehind, meaning the the match is preceded by "The wine"
, with word breaks on either side. .*
matches zero or more characters, as many as possible, meaning the remaining characters in the string.
One more example for given_str = "The wine"
:
doit "Go to The winery for The wine", given_str
#=> "Go to The winery for The wine"
Without the word breaks (\b
) this would be:
doit "Go to The winery for The wine", given_str
#=> "Go to The wine"
The question does not tell me which result is desired.
Upvotes: 0
Reputation: 369458
I don't quite understand the problem.
If you know what the first part of the string is, and you only want to keep the first part of the string, there is no need to do anything, because you already know what the first part of the string is.
if string.start_with?(string_to_keep)
string_to_keep
end
Upvotes: 2
Reputation: 13867
key_string = "The Cuvée"
example_string_1 = "The Cuvée toto 1234"
example_string_2 = "1234 The Cuvée"
index
will return the first occurrence of the key string in your examples. You can then return everything including the first occurrence of your key string with slice
, like:
result1 = example_string_1.slice(0, example_string_1.index(key_string) + key_string.length)
=> "The Cuvée"
result2 = example_string_2.slice(0, example_string_2.index(key_string) + key_string.length)
=> "1234 The Cuvée"
Upvotes: 0
Reputation: 2964
Well, this is what I did:
if string.start_with? string_to_keep
new_string = string[0.. string_to_keep.length-1]
end
Surely not the best Ruby way, but working...
Upvotes: 1