Regular expression to match letter inside brackets - ruby

I need to write a regular expression that matches all strings containing one or more of the following substrings (including the curly brackets):
{NN}
{NNN}
{NNNN}
{NNNNN}
{NNNNNN}
I am completely new to regular expressions. Can anybody help?

r = /
\{ # match left brace
N{2,6} # match between 2 and 6 Ns
\} # match right brace
/x # free-spacing regex definition mode
arr = %w|{N} {NN} {NNN} {NNNN} {NNNNN} {NNNNNN} {NNNNNNN} {NNMN}|
#=> ["{N}", "{NN}", "{NNN}", "{NNNN}", "cat{NNNNN}dog", "{NNNNNN}",
# "{NNNNNNN}", "{NNMN}"]
arr.each { |s| puts "'#{s}'.match(r) = #{s.match?(r)}" }
'{N}'.match(r) = false
'{NN}'.match(r) = true
'{NNN}'.match(r) = true
'{NNNN}'.match(r) = true
'cat{NNNNN}dog'.match(r) = true
'{NNNNNN}'.match(r) = true
'{NNNNNNN}'.match(r) = false
'{NNMN}'.match(r) = false

You didn't specify language / interface you'd be using... In general: \{.*?\} . Replace .*? with N{2,6}? if you want to match only the string you presented.
Ruby example:
if ( content =~ /\{N{2,6}\}/ )
puts "Content match!"
end

Related

ruby regular expression to remove the last occurrence

how to use a ruby regular expression to remove left to right with the last /
example: C:/Users/sino/Documents/window/testing.mp4
the result: testing.txt
thank you for helping me
Use File.basename
File.basename("C:/Users/sino/Documents/window/testing.mp4")
If you still want the regular expression, then
a="C:/Users/sino/Documents/window/testing.mp4"
p a.gsub(/.*\//,"")
Output
testing.mp4
Though I prefer the use of File.basename, as suggested by #Rajagopalen, here are two more ways to obtain the desired result.
str1 = "C:/Users/sino/Documents/window/testing.mp4"
str2 = "testing.mp4"
R = /
[^\/]+ # match one or more characters other than a forward slash
\z # match end of string
/x # free-spacing regex definition mode
or, equivalently,
R = /[^\/]+\z/
str1[R]
#=> "testing.mp4"
str2[R]
#=> "testing.mp4"
(idx = str1.rindex('/')) ? str1[idx+1..-1] : str1
#=> "testing.mp4"
(idx = str2.rindex('/')) ? str2[idx+1..-1] : str2
#=> "testing.mp4"
See String#rindex.

Replacing hyphens in words with the next letter capitalized

I have a symbol like the following. Whenever the symbol contains the "-" hyphen mark, I want to remove it and upcase the subsequent letter.
I am able to do it like so:
sym = :'new-york'
str = sym.to_s.capitalize
/-(.)/.match(str)
str = str.gsub(/-(.)/,$1.capitalize)
=> "NewYork"
This required four lines. Is there a more elegant way to create CamelCase (upper CamelCase e.g. NewYork, NewJersey, BucksCounty) from hyphened words in Ruby?
Here's one way:
sym.to_s.split('-').map(&:capitalize).join #=> "NewYork"
sym.to_s.gsub(/(-|\A)./) { $&[-1].upcase }
or
sym.to_s.gsub(/(-|\A)./) { |m| m[-1].upcase }
r = /
([[:alpha:]]+) # match 1 or more letters in capture group 1
- # match a hyphen
([[:alpha:]]+) # match 1 or more letters in capture group 2
/x # free-spacing regex definition mode
sym = :'new-york'
sym.to_s.sub(r) { $1.capitalize + $2.capitalize }
#=> "NewYork"

Ruby Regular Expression If String has optional period, confirm only 0-2 digits follow

I want to write a regular expression with the following conditions:
string can contain 0-1 period
if the string contains a period: have no more than two digits afterwards
Test conditions:
The following would pass the regex:
'foo'
'foo.'
'foo.1'
'foo.11'
''
'.'
'.1'
'.11'
'1'
'1.'
'1.1'
'1.11'
The following would fail the regex:
'.123'
'.1234'
'.a'
'.1a'
'.aa'
'.aaa'
I have been playing around with trying to get this to work on rubular for a bit now and am struggling.
a = %w(foo foo. foo.1 foo.11 . .1 .11 1 1. 1.1 1.11 .123 .1234 .a .1a .aa .aaa) + ['']
a.grep(/^\w*\.?(\d){0,2}$/m)
=> ["foo", "foo.", "foo.1", "foo.11", ".", ".1", ".11", "1", "1.", "1.1", "1.11", ""]
r = /
\A # match beginning of string
[^.]* # match >= 0 characters other than a period
\.? # optionally match a period
\d{,2} # match 0-2 digits
\z # match end of string
/x # free-spacing regex definition mode
(%w| foo foo. foo.1 foo.11 . .1 .11 1 1. 1.1 1.11 ^$. | << '').all? { |s| s =~ r }
#=> true
(%w| .123 .1234 .a .1a .aa .aaa |).any? { |s| s =~ r }
#=> false

Renaming files by string from array?

I have an array of string pairs.
For example: [["vendors", "users"], ["jobs", "venues"]]
I have a list of files within a directory:
folder/
-478_accounts
-214_vendors
-389_jobs
I need somehow to rename files with the second value from subarrays so it would look like this:
folder/
-478_accounts
-214_users
-389_venues
How do I resolve the problem?
folder = %w| -478_accounts -214_vendors -389_jobs |
#=> ["-478_accounts", "-214_vendors", "-389_jobs"]
h = [["vendors", "users"], ["jobs", "venues"]].to_h
#=> {"vendors"=>"users", "jobs"=>"venues"}
r = Regexp.union(h.keys)
folder.each { |f| File.rename(f, f.sub(r,h)) if f =~ r }
I've used the form of String#sub that employs a hash to make the substitution.
You might want to refine the regex to require the string to be replaced to follow an underscore and be at the end of the string.
r = /
(?<=_) # match an underscore in a positive lookbehind
#{Regexp.union(h.keys)} # match one of the keys of `h`
\z # match end of string
/x # free-spacing regex definition mode
#=> /
# (?<=_) # match an underscore in a positive lookbehind
# (?-mix:vendors|jobs) # match one of the keys of `h`
# \z # match end of string
# /x
You don't have to use a regex.
keys = h.keys
folder.each do |f|
prefix, sep, suffix = f.partition('_')
File.rename(f, prefix+sep+h[suffix]) if sep == '_' && keys.include?(suffix)
end

Regex matching except when pattern is after another pattern

I am looking to find method names for python functions. I only want to find method names if they aren't after "def ". E.g.:
"def method_name(a, b):" # (should not match)
"y = method_name(1,2)" # (should find `method_name`)
My current regex is /\W(.*?)\(/.
str = "def no_match(a, b):\ny = match(1,2)"
str.scan(/(?<!def)\s+\w+(?=\()/).map(&:strip)
#⇒ ["match"]
The regex comments:
negative lookbehind for def,
followed by spaces (will be stripped later),
followed by one or more word symbols \w,
followed by positive lookahead for parenthesis.
Sidenote: one should never use regexps to parse long strings for any purpose.
I have assumed that lines that do not contain "def" are of the form "[something]=[zero or more spaces][method name]".
R1 = /
\bdef\b # match 'def' surrounded by word breaks
/x # free-spacing regex definition mode
R2 = /
[^=]+ # match any characters other than '='
= # match '='
\s* # match >= 0 whitespace chars
\K # forget everything matched so far
[a-z_] # match a lowercase letter or underscore
[a-z0-9_]* # match >= 0 lowercase letters, digits or underscores
[!?]? # possibly match '!' or '?'
/x
def match?(str)
(str !~ R1) && str[R2]
end
match?("def method_name1(a, b):") #=> false
match?("y = method_name2(1,2)") #=> "method_name2"
match?("y = method_name") #=> "method_name"
match?("y = method_name?") #=> "method_name?"
match?("y = def method_name") #=> false
match?("y << method_name") #=> nil
I chose to use two regexes to be able to deal with both my first and penultimate examples. Note that the method returns either a method name or a falsy value, but the latter may be either false or nil.

Resources