Get a string using regular expressin in ruby - ruby

I have some strings like this
../..//somestring
../somestring
../..somestring
./somestring
How to write a regular expression in ruby to extract "somestring" from above strings. Before some strings it can be any combination of . and /
Thanks for you help

Do this:
string.sub(/\A[.\/]+/, "")
"../../test/file/cases".sub(/\A[.\/]+/, "")
# => "test/file/cases"

Just match letters:
str = "../..//somestring" # or "../somestring", "../..somestring", "./somestring"
str[/[a-z]+/] # somestring
RE: your comment
If you just want to remove leading dots and slashes, use
str.gsub(/[.\/]/, '')

It looks like you're dealing with file paths. If so, there are more appropriate tools than regexps
File.basename('../..//somestring')
# "somestring"

regexp = /^[.\/]+(.*?)$/i
result = subject.scan(regexp)
http://rubular.com/r/tMYKPe78uc

Related

Ruby regex: operator and

I have an string of an email that looks like "<luke#example.com>"
I would like to use regex for deleting "<" and ">", so I wanted something like
"<luke#example.com>".sub /<>/, ""
The problem is quite clear, /<>/ doesn't wrap what I want. I tried with different regex, but I don't know how to choose < AND >, it is there any and operator where I can say: "wrap this and this"?
As written, your regex matches the literal substring "<>" only. You need to use [] to make them a character class so that they're matched individually, and gsub to replace all matches:
"<luke#example.com>".gsub(/[<>]/, "") # => "luke#example.com"
"<luke#example.com>".gsub /[<>]/, ""
http://regex101.com/r/hP3sY2
If you only ever want to strip the < and > from the start and end only, you can use this:
'<luke#example.com>'.sub(/\A<([^<>]+)>\z/, '\1')
You don't need, nor should you use, a regex.
string[1..-2]
is enough.

regex replace [ with \[

I want to write a regex in Ruby that will add a backslash prior to any open square brackets.
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
# desired out = "my.name\[0].hello.line\[2]"
I've tried multiple combinations of backslashes in the substitution string and can't get it to leave a single backslash.
You don't need a regular expression here.
str = "my.name[0].hello.line[2]"
puts str.gsub('[', '\[')
# my.name\[0].hello.line\[2]
I tried your code and it worked correct:
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
puts out #my.name\[0].hello.line\[2]
If you replace putswith p you get the inspect-version of the string:
p out #"my.name\\[0].hello.line\\[2]"
Please see the " and the masked \. Maybe you saw this result.
As Daniel already answered: You can also define the string with ' and don't need to mask the values.

Check that a string exists within another string with regular expression

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?
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)$/, "")
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.
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

How do I strip parenthesis from a string in Ruby?

I have a string, like this:
"yellow-corn-(corn-on-the-cob)"
and I would like to strip the parenthesis from the string to get something like this:
"yellow-corn-corn-on-the-cob"
I believe you would use gsub to accomplish this, but I'm not sure what pattern I would need to match the parenthesis. Something like:
clean_string = old_string.gsub(PATTERN,"")
Without regular expression:
"yellow-corn-(corn-on-the-cob)".delete('()') #=> "yellow-corn-corn-on-the-cob"
Try this:
clean_string = old_string.gsub(/[()]/, "")
On a side note, Rubular is awesome to test your regular expressions quickly.

Regex to leave desired string remaining and others removed

In Ruby, what regex will strip out all but a desired string if present in the containing string? I know about /[^abc]/ for characters, but what about strings?
Say I have the string "group=4&type_ids[]=2&type_ids[]=7&saved=1" and want to retain the pattern group=\d, if it is present in the string using only a regex?
Currently, I am splitting on & and then doing a select with matching condition =~ /group=\d/ on the resulting enumerable collection. It works fine, but I'd like to know the regex to do this more directly.
Simply:
part = str[/group=\d+/]
If you want only the numbers, then:
group_str = str[/group=(\d+)/,1]
If you want only the numbers as an integer, then:
group_num = str[/group=(\d+)/,1].to_i
Warning: String#[] will return nil if no match occurs, and blindly calling nil.to_i always returns 0.
You can try:
$str =~ s/.*(group=\d+).*/\1/;
Typically I wouldn't really worry too much about a complex regex. Simply break the string down into smaller parts and it becomes easier:
asdf = "group=4&type_ids[]=2&type_ids[]=7&saved=1"
asdf.split('&').select{ |q| q['group'] } # => ["group=4"]
Otherwise, you can use regex a bunch of different ways. Here's two ways I tend to use:
asdf.scan(/group=\d+/) # => ["group=4"]
asdf[/(group=\d+)/, 1] # => "group=4"
Try:
str.match(/group=\d+/)[0]

Resources