How do I strip parenthesis from a string in Ruby? - 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.

Related

Replace text in brackets gsub

I would like to replace text inside of brackets, and that has a colon and a u.
For example, Here is a link [u:person]! would become Here is a link Person! I am not very experienced with regex, and I am having problems with \1 and $1
Here is the regex that I am using now:
string.gsub(/\[(\w*).*?\]/, "<a href='/user/\1'>\1</a>")
Make the regex /\[\w*:(.*?)\]/ so that person can be captured instead of u. Then use a single quoted string so that \1 isn't interpreted as \x01.
str = "Here is a link [u:person]!"
puts str.gsub(/\[\w*:(.*?)\]/, '\1')
# => Here is a link person!
I changed your regular expression to this, so that person is captured:
/\[\w*:(.*?)\]/
And then replaced it with this String:
"#{$1.capitalize}"
You were close with $1, it just needs to be evaluated as Ruby (using String interpolation, inside a block):
string.gsub(/\[\w*:(.*?)\]/) { "#{$1.capitalize}" }
You could use a regex like this:
/\[u\:([\S]+)\]/
and replace it with:
<a href='/user/#{$1}'>#{$1}</a>
Here's a breakdown of what it the regex does:
First, we have \[, which is just the literal [ character
Next, we have u and \:, which are the literal u and : character respectively
Next, we have ([\S]). The parentheses make a capturing group, which is what #{$1} will be filled in with in the replace part of the regex. [\S]+ looks for all non-whitespace characters.
Lastly, we have \], which is just the literal ] character.
Your code should look something like this:
string.gsub('/\[u\:([\S]+)\]/', '<a href='/user/#{$1}'>#{$1}</a>')
Here is a live test of the regex: https://regex101.com/r/vK0iO2
\[[^\]]*u:([^\]]*)\]
Try this.Replace by <a href='/user/\1'>\1</a>.See demo.
https://regex101.com/r/gX5qF3/13

Ruby Regex Rubular vs reality

I have a string and I want to remove all non-word characters and whitespace from it. So I thought Regular expressions would be what I need for that.
My Regex looks like that (I defined it in the string class as a method):
/[\w&&\S]+/.match(self.downcase)
when I run this expression in Rubular with the test string "hello ..a.sdf asdf..," it highlioghts all the stuff I need ("hellloasdfasdf") but when I do the same in irb I only get "hello".
Has anyone any ideas about why that is?
Because you use match, with returns one matching element. If you use scan instead, all should work properly:
string = "hello ..a.sdf asdf..,"
string.downcase.scan(/[\w&&\S]+/)
# => ["hello", "a", "sdf", "asdf"]
\w means [a-zA-Z0-9_]
\S means any non-whitespace character [a-zA-Z_-0-9!##$%^&*\(\)\\{}?><....etc]
so using a \w and \S condition is ambiguous.
Its like saying What is an intersection of India and Asia. Obviously its going to be India. So I will suggest you to use \w+.
and you can use scan to get all matches as mentioned in the second answer :
string = "hello ..a.sdf asdf..,"
string.scan(/\w+/)

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.

Get a string using regular expressin in 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

Wrap parentheses

I'm trying to wrap parentheses around string in ruby, only if it isn't wrapped yet:
"my string (to_wrap)" => "my string (to_wrap)"
"my string to_wrap" => "my string (to_wrap)"
I've tried something like:
to_wrap = 'to_wrap'
regexp = Regexp.new "(?!\()#{to_wrap}(?!\))"
string.sub(regexp, "(#{to_wrap})")
but it does not work.
Thanks in advance!
You are very close. Your first negative lookaround is a lookahead, though. So it looks at the first character of to_wrap. Just make that a lookbehind:
"(?<!\()#{to_wrap}(?!\))"
And just to present you with an alternative option to escape parentheses (it's really a matter of taste which on to use, but I find it more easily readable):
"(?<![(])#{to_wrap}(?![)])"

Resources