[Ruby] How do I use advanced string manipulation techniques (e.g., regular expressions) in Ruby?

To use advanced string manipulation techniques like regular expressions in Ruby, you can take advantage of the built-in Regexp class and its methods. Here are the basic steps to use regular expressions in Ruby:

  1. Create a regular expression pattern using the Regexp.new method or by using the /pattern/ syntax. For example, to match all occurrences of the word "hello" in a string, you can use /hello/.

  2. You can use regular expression methods like match, scan, gsub, sub, etc., to perform various string manipulation operations.

  • match method: This method returns the first match of the pattern in the string or nil if no match is found. It returns a MatchData object that contains information about the match.
1string = "Hello, World!"
2match_data = /Hello/.match(string)
3puts match_data.to_s  # Outputs: "Hello"
  • scan method: This method returns an array of all matches found in the string.
1string = "Hello, Hello, Hello!"
2matches = string.scan(/Hello/)
3puts matches.inspect  # Outputs: ["Hello", "Hello", "Hello"]
  • gsub method: This method replaces all occurrences of the pattern with the specified replacement string.
1string = "Hello, world!"
2new_string = string.gsub(/Hello/, "Hi")
3puts new_string  # Outputs: "Hi, world!"
  • sub method: This method replaces only the first occurrence of the pattern with the specified replacement string.
1string = "Hello, Hello, Hello!"
2new_string = string.sub(/Hello/, "Hi")
3puts new_string  # Outputs: "Hi, Hello, Hello!"

You can also use various regular expression modifiers and metacharacters like ^, $, *, +, ?, etc., to build complex patterns. Additionally, Ruby provides numerous methods to manipulate and extract information from the MatchData object returned by the match method.

Regular expressions offer powerful string manipulation capabilities, and it's worth exploring the Ruby documentation or online resources for more in-depth usage and examples.