[JAVA] Regular expression basics


Let's take a look at regular expressions using irb.


irb(main):001:0> name = "taro"
=> "taro"
irb(main):002:0> name.sub(/taro/,"kotaro")
=> "kotaro"

I'm using the sub method to replace the word taro with kotaro. Specify the character string to be replaced in the first argument, and describe the converted character string in the second argument.

irb(main):004:0> name.match(/taro/)
=> #<MatchData "taro">
irb(main):005:0> name.match(/bob/)
=> nil

The match method is used to check if the specified string is included in the argument. If it is included, the specified string will be returned as a MatchData object as a return value. If it is not included, nil will be returned.

irb(main):006:0> array = name.match(/taro/)
=> #<MatchData "taro">
irb(main):007:0> array[0]
=> "taro"

Since the MatchData object is an array, you can get the value by doing the above.

irb(main):008:0> phoneNumber = "080-1234-5678"
=> "080-1234-5678"
irb(main):009:0> phoneNumber.gsub(/-/,"")
=> "08012345678"

If you want to get rid of hyphens in your phone number, use the gsub method because using the sub method will only replace the first hyphen. g is a global match that replaces all of the specified strings if they are included.

irb(main):010:0> myPassword = "Taro0123"
=> "Taro0123"
irb(main):012:0> myPassword.match(/[a-z\d]{8,10}/i)
=> #<MatchData "Taro0123">
irb(main):013:0> myPassword.match(/[a-c\d]/i)
=> #<MatchData "a">
irb(main):014:0> myPassword.match(/[a-c\d]{8,}/i)
=> nil

・ [A-z] matches any one of the letters a to z ・ \ D matches the number ・ {8,10} matches the character string that appears at least 8 times and at most 10 times. ・ I searches in a case-insensitive manner is what it means.

irb(main):015:0> myAddress = "[email protected]"
=> "[email protected]"
irb(main):016:0> myAddress.match(/@.+/)
=> #<MatchData "@gmail.jp">

To get the domain of your email address . Matches any single character

Thank you for reading this article.

Recommended Posts

Regular expression basics
JS regular expression
Ruby regular expression
unicode regular expression sample
Regular expression for password
java regular expression summary
Full-width / half-width judgment regular expression
A little regular expression story Part 1
A little regular expression story Part 2
Regular expressions
Rails basics
Ruby basics
Ruby basics
Apply regular expression matching with JSON Sassert
Fragment basics
JPA Basics 1
Docker basics
ViewPager basics
Java basics
Ruby: Regular expression summary * Code sample available
RSpec Basics
JavaScript basics
JPA Basics 2
Hash basics
Java basics
Ruby basics
RecyclerView Basics
/ Mask delimited user ID / password password with regular expression