0

I've got a regular expression that I am using to strip an extension from another string

The extensions in this example are

BK|BZ|113

If the string does not contain any of the extensions, then I need it to leave the string as is.

The regular expression I'm using is

base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1]

However, if the base_value does not contain the string, I want to return the base_value. I thought I could use

base_value = base_string
base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] unless (base_value !~ /(.*?[^-])-?(?:BK|BZ|113)) == false

but that isn't working.

What is the best way to return the base_string if the extensions are not found?

1
  • 3
    Can you give some example inputs? Commented Sep 28, 2011 at 22:52

3 Answers 3

2

If I understand well, you want to strip the regexp from a string, if it matches, right? So.. do it:

string.sub(/(?:BK|BZ|113)$/, "")
Sign up to request clarification or add additional context in comments.

1 Comment

Your approach is the better than mine, I guess I got stuck on what he had written, up!
0

Perhaps you can use sub like this:

base_string1 = "test1BK"
base_string2 = "test2"

p base_string1.sub(/(.*?[^-])-?(?:BK|BZ|113)/,'\1')
p base_string2.sub(/(.*?[^-])-?(?:BK|BZ|113)/,'\1')

When the pattern is not found nothing is replaced, otherwise it returns the string without the extension.

Comments

0

If /(.*?[^-])-?(?:BK|BZ|113)/ doesn't match then base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] will be nil. So this should work:

base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] || base_string

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.