Using regex to match characters in a string

Thanks ahead of time, sorry if this is dumb, but I for the life of me cannot nail this down.

(Example)

match_string = “This Is The String”
matching = /[a-z]+\s/.match(match_string)
puts matching


All I want to grab is all of the lowercase characters and print them out, but I seem to not be able to find a way to do it this way. I know the regex above is not correct in what I want and is just a example, but I have been trying different patterns for the last hour, still cannot seem to get what I want.

Any Suggestions?

Well, the matching = /[a-z]+\s/.match(match_string) returns the first match in the string, that is his.

The easiest way to do what you’re describing is replacing non-lowercase: puts match_string.gsub(/[^a-z\s]+/, "")

1 Like

If you want multiple matches, String#scan is your best bet.

match_string = "This Is The String"
matching = match_string.scan(/[a-z]+/)
pp matching
# [Regex::MatchData("his"),
#  Regex::MatchData("s"),
#  Regex::MatchData("he"),
#  Regex::MatchData("tring")]
3 Likes

Very interesting, thank you!!

I did not know about this gsub, thank you very much!

You might also consider some non-regex implementations that simply remove uppercase characters:

puts "This Is The String".delete &.uppercase?
puts "This Is The String".delete("A-Z")
4 Likes

Oh nice, that’s pretty cool. Thank you for that.