FEE
FEE

Reputation: 309

Remove everything after some characters

I have two situations:

In the first, I may have a string like:

  Posted 03-20-2017 More info Go to Last Post

And I may have a string like:

  Posted today More info Go to Last Post

In both of the situations, I don't want anything from More Info...

I tried using gsub,but it doesn't work for both of the situations. Does anyone have possible solution?

Upvotes: 1

Views: 3134

Answers (2)

octopushugs
octopushugs

Reputation: 157

This can be relatively easily accomplished by running split("More info") on your strings. What that does is breaks the string in to an array like so:

new_string  = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]

What split does is it breaks a string apart in to an array, where each element is what preceded the argument. So if you have "1,2,3" then split(",") will return [1, 2, 3]

So to continue your solution, you can get the posting date like this:

new_string[0].strip

.strip removes spaces at the front or back of a string, so you'll be left with just "Posted today"

Upvotes: 2

Sebastián Palma
Sebastián Palma

Reputation: 33420

Use the Ruby sub, which will give you a copy the first occurrence of pattern substituted for the second argument.

So it'll take your whole string "Posted 03-20-2017 More info Go to Last Post", will find your pattern and all what comes after More info..., and will replace it with the second argument More info, that in this case is the same as first (you can use a variable there).

"Posted 03-20-2017 More info Go to Last Post".sub /More info.*/, 'More info'
=> "Posted 03-20-2017 More info"

Also gsub works in a similar way.

Upvotes: 1

Related Questions