The two regexes:
regex_1 = /^A+\S{2}$/
regex_2 = /^AB+\d{1}$/
match the following ten strings:
AB0
AB1
AB2
AB3
AB4
AB5
AB6
AB7
AB8
AB9
Is there a way to find strings that match two regular expressions that are given?
I have a regex, and it will be sliced to many sub-regexes as follows.
Example 1:
original_regex = /^A+\S{2}$/
sub_regex1 = /^AB+\S{1}$/
sub_regex2 = /^AC+\S{1}$/
Example 2:
original_regex = /^598+\S{5}$/
sub_regex1 = /^598A+\S{4}$/
sub_regex2 = /^598AB+\S{3}$/
I want to know whether there are any strings that match all sub-regexes.
I am thinking to convert the regex to a string and compare the minimal-length prefix and the minimal-length suffix like this:
regex_1 = "/^A+\S{2}$/"
regex_2 = "/^AB+\d{1}$/"
regex_3 = "/^AC+\d{1}$/"
minimal_prefix = "/^A"
Any regex string that contains minimal_prefix has a string that matches all sub-regexes. I am figuring out whether this is correct or not.
Is there a quick way in general? No. What are "all the strings" that match these pairs of regular expressions:
/.*/ and /\d*/? (There are infinitely many!)
/\A\d{10}\z/ and /\A[0-8]{10}\z/? (There are 3,486,784,401!)
/\w+\d{2,4}#?([[:punct:]]|\w){2}/ and /(^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)/ (I haven't even tried to work this out; my point is: you could provide arbitrarily complicated input!!)
...But for simple scenarios, such as what you've actually asked, it would be feasible to use this ruby gem:
/^A+\S{2}$/.examples(max_group_results: 999) & /^AB+\d{1}$/.examples(max_group_results: 999)
=> ["AB0", "AB1", "AB2", "AB3", "AB4", "AB5", "AB6", "AB7", "AB8", "AB9"]
Related
I've printed the code, wit ruby
string = "hahahah"
pring string.gsub("a","b")
How do I add more letter replacements into gsub?
string.gsub("a","b")("h","l") and string.gsub("a","b";"h","l")
didnt work...
*update I have tried this too but without any success .
letters = {
"a" => "l"
"b" => "n"
...
"z" => "f"
}
string = "hahahah"
print string.gsub(\/w\,letters)
You're overcomplicating. As with most method calls in Ruby, you can simply chain #gsub calls together, one after the other:
str = 'adfh'
print str.gsub("a","b").gsub("h","l") #=> 'bdfl'
What you're doing here is applying the second #gsub to the result of the first one.
Of course, that gets a bit long-winded if you do too many of them. So, when you find yourself stringing too many together, you'll want to look for a regex solution. Rubular is a great place to tinker with them.
The way to use your hash trick with #gsub and a regex expression is to provide a hash for all possible matches. This has the same result as the two #gsub calls:
print str.gsub(/[ah]/, {'a'=>'b', 'h'=>'l'}) #=> 'bdfl'
The regex matches either a or h (/[ah]/), and the hash is saying what to substitute for each of them.
All that said, str.tr('ah', 'bl') is the simplest way to solve your problem as specified, as some commenters have mentioned, so long as you are working with single letters. If you need to work with two or more characters per substitution, you'll need to use #gsub.
How can I match a string against multiple patterns using regular expression in ruby.
I am trying to see if a string is included in an array of prefixes, This is not working but I think it demonstrates at least what I am trying to do.
# example:
# prefixes.include?("Mrs. Kirsten Hess")
prefixes.include?(name) # should return true / false
prefixes = [
/Ms\.?/i,
/Miss/i,
/Mrs\.?/i,
/Mr\.?/i,
/Master/i,
/Rev\.?/i,
/Reverend/i,
/Fr\.?/i,
/Father/i,
/Dr\.?/i,
/Doctor/i,
/Atty\.?/i,
/Attorney/i,
/Prof\.?/i,
/Professor/i,
/Hon\.?/i,
/Honorable/i,
/Pres\.?/i,
/President/i,
/Gov\.?/i,
/Governor/i,
/Coach/i,
/Ofc\.?/i,
/Officer/i,
/Msgr\.?/i,
/Monsignor/i,
/Sr\.?/i,
/Sister\.?/i,
/Br\.?/i,
/Brother/i,
/Supt\.?/i,
/Superintendent/i,
/Rep\.?/i,
/Representative/i,
/Sen\.?/i,
/Senator/i,
/Amb\.?/i,
/Ambassador/i,
/Treas\.?/i,
/Treasurer/i,
/Sec\.?/i,
/Secretary/i,
/Pvt\.?/i,
/Private/i,
/Cpl\.?/i,
/Corporal/i,
/Sgt\.?/i,
/Sargent/i,
/Adm\.?/i,
/Administrative/i,
/Maj\.?/i,
/Major/i,
/Capt\.?/i,
/Captain/i,
/Cmdr\.?/i,
/Commander/i,
/Lt\.?/i,
/Lieutenant/i,
/^Lt Col\.?$/i,
/^Lieutenant Col$/i,
/Col\.?/i,
/Colonel/i,
/Gen\.?/i,
/General/i
]
Use Regexp.union to combine them:
union(pats_ary) → new_regexp
Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts.
So this will do:
re = Regexp.union(prefixes)
then you use re as your regex:
if name.match(re)
#...
If you can use a single string, it might be faster to write a regex containing the possible values.
e.g.
/(Mr\.|Mrs\.| ... )/.match(name)
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]
I'm working on 2 cases:
assume I have those var:
a = "hello"
b = "hello-SP"
c = "not_hello"
Any partial matches
I want to accept any string that has the variable a inside, so b and c would match.
Patterned match
I want to match a string that has a inside, followed by '-', so b would match, c does not.
I am having problem, because I always used the syntax /expression/ to define Regexp, so how dynamically define an RegExp on Ruby?
You can use the same syntax to use variables in a regex, so:
reg1 = /#{a}/
would match on anything that contains the value of the a variable (at the time the expression is created!) and
reg2 = /#{a}-/
would do the same, plus a hyphen, so hello- in your example.
Edit: As Wayne Conrad points out, if a contains "any characters that would have special meaning in a regular expression," you need to escape them. Example:
a = ".com"
b = Regexp.new(Regexp.escape(a))
"blah.com" =~ b
Late to comment but I wasn't able to find what I was looking for.The above mentioned answers didn't help me.Hope it help someone new to ruby who just wants a quick fix.
Ruby Code:
st = "BJ's Restaurant & Brewery"
#take the string you want to match into a variable
m = (/BJ\'s/i).match(string) #(/"your regular expression"/.match(string))
# m has the match #<MatchData "BJ's">
m.to_s
# this will display the match
=> "BJ's"
I have following string:
"xxxxx GL=>G0 yyyyyy "
I want to extract GL and G0 using ruby regular expression.
Thanks.
Well, this is rather vague. Do you want to pull out key/value pairs when separated by => ?
The following regexp may suit your needs:
matches = /.*(\w{2})=>(\w{2}).*/.match("xxxxxx GL=>G0 yyyyy ")
puts matches[1] // GL
puts matches[2] // G0
This assumes that your key/values are 2 characters long separated by a => sign. It does not permit spaces between the characters and the => sign. Let me know if this is what you need. Otherwise, provide a more detailed description of what strings you may need to parse.