subject = 'Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}' regex = /{[^}]+}|"Tarzan\d+"|(Tarzan\d+)/ # put Group 1 captures in an array group1Caps = [] subject.scan(regex) {|m| group1Caps << 1ドル if !1ドル.nil? } ######## The six main tasks we're likely to have ######## # Task 1: Is there a match? puts("*** Is there a Match? ***") if group1Caps.length > 0 puts "Yes" else puts "No" end # Task 2: How many matches are there? puts "\n*** Number of Matches ***" puts group1Caps.length # Task 3: What is the first match? puts "\n*** First Match ***" if group1Caps.length > 0 puts group1Caps[0] end # Task 4: What are all the matches? puts "\n*** Matches ***" if group1Caps.length > 0 group1Caps.each { |x| puts x } end # Task 5: Replace the matches replaced = subject.gsub(regex) {|m| if 1ドル.nil? m else "Superman" end } puts "\n*** Replacements ***" puts replaced # Task 6: Split # Start by replacing by something distinctive, # as in Step 5. Then split. splits = replaced.split(/Superman/) puts "\n*** Splits ***" splits.each { |x| puts x }
Standard input is empty
*** Is there a Match? ***
Yes
*** Number of Matches ***
2
*** First Match ***
Tarzan11
*** Matches ***
Tarzan11
Tarzan22
*** Replacements ***
Jane"" ""Tarzan12"" Superman@Superman {4 Tarzan34}
*** Splits ***
Jane"" ""Tarzan12""
@
{4 Tarzan34}
The brand new service which powers Ideone!
Widget for compiling and running the source code in a web browser!