As the title suggests, it extracts a string that starts with a capital letter in a regular expression.
The code I wrote this time is as follows
#A method to extract a string starting with a capital letter from an array
def upperstr(array)
#Variables used as array subscripts
count = 0
#An array that stores strings starting with an uppercase letter
upper = []
#Extract all the elements contained in the array with each method
array.each{|arraystr|
#Extracts strings that start with a capital letter in a regular expression and arranges them(upper)Store in
upper[count] = arraystr.slice(/^[A-Z].*/)
#Add 1 to the array subscript
count += 1
}
#If the beginning of the character string is lowercase, nil is stored in the array, so delete nil with the delete method.
upper.delete(nil)
#As the return value of the method, change the array that stores the character string starting with a capital letter.
return upper
end
#User's guide
p "Enter the character strings separated by a space."
#Assign a string entered from the console to a variable
str = gets
#Separate the input character string with a space and assign it to the array
ary = str.split(" ")
#Assign the return value of the upperstr method to a variable
# (The upperstr method is a method that extracts a string starting with an uppercase letter.)
upperary = upperstr(ary)
#User's guide
p "I took out a string starting with a capital letter"
#Extract all the elements contained in the array with each method
upperary.each{|ustr|
#Show the contents of the array
p ustr
}
① Code upper[count] = arraystr.slice(/[1].*/)
②/ The range surrounded by / and / is the range of the regular expression pattern.
③^ Indicates that the character immediately after ^ is the first character
④[A-Z] It means A to Z, which means it is capitalized. You can search for a character string that starts with an uppercase letter by typing ^ [A-Z]. If you want to make it lowercase, use [a-z].
⑤. . Is any one character.
⑥*
I will write the result of actually running the program. The input value is "aaa AAA B b CC cc DDDDD ddddd". It retrieves strings that start with an uppercase letter, so the expected result is "AAA B CC DDDDD".
% ruby regex.rb
"Enter the character strings separated by a space."
aaa AAA B b CC cc DDDDD ddddd
"I took out a string starting with a capital letter"
"AAA"
"B"
"CC"
"DDDDD"
The result was as expected! That's all for this article!
A-Z ↩︎
Recommended Posts