What would the regex be to detect this string? - ruby

I need to determine if a given string has the sequence dash-alpha-alpha-dash.
Example strings:
114888-ZV-209897
409-II-224858
86296-MO-184080
2459-ND-217906
What would be the the regex to determine that?
I'm using Ruby 1.9.3, FWIW.

if subject =~ /-[A-Z]{2}-/
# Successful match
else
# Match attempt failed
end
That [A-Z] thingy is a character class.

It's a simple pattern:
/-[A-Z]{2}-/
will do it.
Your regex is available at: http://rubular.com/r/6hn8BLc7rF
For instance:
"114888-ZV-209897"[/-[A-Z]{2}-/]
=> "-ZV-"
So use:
if "114888-ZV-209897"[/-[A-Z]{2}-/] ...

Related

Ruby regular expression to get users names after # symbol

How can I get the username without the # symbol?
That's everything between # and any non-word character.
message = <<-MESSAGE
From #victor with love,
To #andrea,
and CC goes to #ghost
MESSAGE
Using a Ruby regular expression, I tried
username_pattern = /#\w+/
I will like to get the following output
message.scan(username_pattern)
#=> ["victor", "andrea", "ghost"]
Use look behind
(?<=#)\w+
this will leave # symbol regex
I would go with:
message.scan(/(?<=#)\w+/)
#=> ["victor","andrea","ghost"]
You might want to read about look-behind regexp.
You could match the # and then capture one or more times a word character in a capturing group
#(\w+)
username_pattern = /#(\w+)/
Regex demo
Try this
irb(main):010:0> message.scan(/#(\w+)/m).flatten
=> ["victor", "andrea", "ghost"]

how to find out one string contains substring in ruby

I am having one string variable need to check substring is present in it, like:
str = "sdfgg"
need to check if str contains df
Please help me to write a code in ruby to check the scenario
Use String#include?.
str.include?("df")
You can also use a regex for that:
if str =~ /df/
# Successful match
else
# Match attempt failed
end

extract with regex, one liner in ruby

I would like to extract the word after "=". For "GENEINFO=AGRN:" in a document, I can use the regex /GENEINFO=(.*?):/ to extract the required. However the value I wanted to returned is just "AGRN". Is there a one-liner that I can use for this task?
Try using a lookbehind and a lookahead:
/(?<=GENEINFO=).*?(?=:)/
You could also use match:
'GENEINFO=AGRN:'.match(/GENEINFO=(.*?):/)[1]
#=> "AGRN"
Which could also be written using the String#[] method:
'GENEINFO=AGRN:'[/GENEINFO=(.*?):/, 1]
#=> "AGRN"
"GENEINFO=AGRN:"[/(?<==).*(?=:)/]
# => "AGRN"
You want a lookbehind and lookahead.
pattern = /(?<=GENEINFO=)(.*?)(?=:)/
value = "GENEINFO=AGRN:".scan(pattern)
// [["AGRN"]]

Regular expression to match a pattern either at the beginning of the line or after a space character

I've been trying to dry up the following regexp that matches hashtags in a string with no success:
/^#(\w+)|\s#(\w+)/i
This won't work:
/^|\s#(\w+)/i
And no, I don't want to comma the alternation at the beginning:
/(^|\s)#(\w+)/i
I'm doing this in Ruby - though that should not be relevant I suppose.
To give some examples of matching and non-matching strings:
'#hashtag it is' # should match => [["hashtag"]]
'this is a #hashtag' # should match => [["hashtag"]]
'this is not a#hashtag' # should not match => []
Any suggestions? Am I nitpicking?
You can use.
/\B#(\w+)/i
"this is a #hash tag" # matches
"#hash tag" # matches
"this is not#hash tag" # doesn't match
/(?:^|\s)#(\w+)/i
Adding the ?: prefix to the first group will cause it to not be a matching group, thus only the second group will actually be a matchgroup. Thus, each match of the string will have a single capturing group, the contents of which will be the hashtag.
This uses look-behind and I don't know if look behinds are supported in Ruby (I heard that they are not supported in JavaScript)
/(^#(\w+))|((?<= )#(\w+))/

Remove character from string if it starts with that character?

How can I remove the very first "1" from any string if that string starts with a "1"?
"1hello world" => "hello world"
"112345" => "12345"
I'm thinking of doing
string.sub!('1', '') if string =~ /^1/
but I' wondering there's a better way. Thanks!
Why not just include the regex in the sub! method?
string.sub!(/^1/, '')
As of Ruby 2.5 you can use delete_prefix or delete_prefix! to achieve this in a readable manner.
In this case "1hello world".delete_prefix("1").
More info here:
https://blog.jetbrains.com/ruby/2017/10/10-new-features-in-ruby-2-5/
https://bugs.ruby-lang.org/issues/12694
'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"
N.B. you can also use this to remove items from the end of a string with delete_suffix and delete_suffix!
'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"
https://bugs.ruby-lang.org/issues/13665
I've answered in a little more detail (with benchmarks) here: What is the easiest way to remove the first character from a string?
if you're going to use regex for the match, you may as well use it for the replacement
string.sub!(%r{^1},"")
BTW, the %r{} is just an alternate syntax for regular expressions. You can use %r followed by any character e.g. %r!^1!.
Careful using sub!(/^1/,'') ! In case the string doesn't match /^1/ it will return nil. You should probably use sub (without the bang).
This answer might be more optimised: What is the easiest way to remove the first character from a string?
string[0] = '' if string[0] == '1'
I'd like to post a tiny improvement to the otherwise excellent answer by Zach. The ^ matches the beginning of every line in Ruby regex. This means there can be multiple matches per string. Kenji asked about the beginning of the string which means they have to use this regex instead:
string.sub!(/\A1/, '')
Compare this - multiple matches with this - one match.

Resources