1

I'm struggling to figure out the proper regex for this.

I have a string that looks something like this: here-is.my.string

I need to return a string that removes everything starting with the dash up to (but not including) the first dot. here.my.string

Thanks.

1
  • If you're struggling with something, you should show your attempts. Commented Dec 4, 2014 at 17:16

2 Answers 2

4

Do this:

puts 'here-is.my.string'.sub(/-[^.]+(?=\.)/, '')

The trick here is the positive look-ahead ((?=\.)), which requires that there is a dot following the match, but does not consider it a part of the match.

Edit:

As Avinash Raj and mudasobwa pointed out in the comments, it's enough to require a greedy sequence of characters that are not dots. This works just as well:

puts 'here-is.my.string'.sub(/-[^.]+/, '')
Sign up to request clarification or add additional context in comments.

2 Comments

i think you don't need a lookahead.
While this works perfectly, the positive look-ahead here is an overkill. /-[^.]+/.
2

Ruby has a bajillion ways to do it. Here's a very simple way:

str = 'here-is.my.string'
str[/-[^.]+/] = ''
str # => "here.my.string"

It just finds the match and assigns '' to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.