Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching capitals

Tags:

regex

ruby

match

 def normalized?

    matches = match(/[^A-Z]*/)
    return matches.size == 0

  end

This is my function operating on a string, checking wether a string contains only uppercase letters. It works fine ruling out non matches, but when i call it on a string like "ABC" it says no match, because apparently matches.size is 1 and not zero. There seems to be an empty element in it or so.

Can anybody explain why?

like image 670
Samuel Avatar asked Dec 28 '22 23:12

Samuel


2 Answers

Your regex is wrong - if you want it to match ONLY uppercase strings, use /^[A-Z]+$/.

like image 127
mway Avatar answered Jan 12 '23 13:01

mway


Your regular expression is incorrect. /[^A-Z]*/ means "match zero or more characters that are not between A and Z, anywhere in the string". The string ABC has zero characters that are not between A and Z, so it matches the regular expression.

Change your regular expression to /^[^A-Z]+$/. This means "match one or more characters that are not between A and Z, and make sure every character between the beginning and end of the string are not between A and Z". Then the string ABC will not match, and then you can check matches[0].size or whatever, as per sepp2k's answer.

like image 23
CanSpice Avatar answered Jan 12 '23 13:01

CanSpice