What is the best way to merge in a single ruby regex fixed characters and the OR (||) 2nd condition not working properly?

Hi,

What is the best way to merge in a single regex to capture the values of fixed {5} or {7} in below sample? Also, my OR (||) doesn’t seem to work in the 2nd condition.

if name =~ /^[sp][ap]\w{5}A\d{2}/ || hostname =~ /^[sp][ap]\w{7}A\d{2}/
   value = 'Valid Test name'
else
   value = 'Invalid Test name'
end

name = 'spongebobA12'    => 'Invalid Test name'
name = 'patrickA34'	 => 'Valid Test name'

Thanks!

You can do something like this:

Code

def testname(name)
	(name[/^[sp][ap](\w{5}|\w{7})A\d{2}/] ? 'Valid' : 'Invalid') << ' Test name'
end

p testname 'spongebobA12'
p testname 'patrickA34'

p testname 'aspongebobA12'
p testname 'apatrickA34'

p testname 'SpongebobA12'
p testname 'PatrickA34'

Note the (\w{5}|\w{7}).

Output

"Valid Test name"
"Valid Test name"
"Invalid Test name"
"Invalid Test name"
"Invalid Test name"
"Invalid Test name"
1 Like