Java Basic Learning Note 13 Regular expressions for common APIs, Date, DateFormat, Calendar

Source: Internet
Author: User
Tags character classes dateformat

Regular expressions

Regular Expressions (English: Regular expression, often abbreviated as regex in code). A regular expression is a string that is described using a single string, used to define a matching rule, and matches a series of strings that conform to a certain syntactic rule. In development, regular expressions are often used to retrieve and replace text that conforms to a rule.

Matching rules for regular expressions

Referring to the help document, there is a rule definition in the pattern class that has a regular expression, which explicitly distinguishes the uppercase and lowercase letters in the regular expression. Let's learn the rules of grammar.

Syntax rules for regular expressions:

"A", then the string content that needs to be matched is "a"
character: \ Meaning: The backslash character ' \ ' for example: The match rule is "\ \", then the string content that needs to be matched is "\"
character: \ t meaning: Tab For example: The matching rule is "\ t", then the corresponding effect is to produce a tab space
character: \ n meaning: line break For example: The match rule is "\ n", then the corresponding effect is a newline, the next line of the cursor in the original position
character: \ r meaning: Carriage return for example: The match rule is "\ r", then the corresponding effect is the effect of carriage return, the cursor comes to the next line beginning
character class: [ABC] Meaning: The character A, b, or C, for example: the matching rule is "[ABC]", then the need to match the content is the character a, or the character B, or the character C of a
Character class: [^ABC] Meaning: represents any character other than a, B, or C For example: The match rule is "[^ABC]", then the match is not the character a, or is not a character B, or is not a character C any character
Character class: [a-za-z] Meaning: represents a to Z or A to Z, the letters at both ends are included for example: the match rule is "[A-za-z]", then the match is a uppercase or lowercase letter
Character class: [0-9] Meaning: represents 0 to 9 digits, both ends of the number are included for example: the match rule is "[0-9]", then need to match is a number
Character class: [a-za-z_0-9] Meaning: The representation of the letter or number or underscore (that is, the word character) For example: The match rule is "[a-za-z_0-9]", then need to match is a letter or a number or a glide line
predefined character classes:. Meaning: Represents any character, for example: The match rule is ". ", then you need to match an arbitrary character. If you want to use it. , use the matching rule "\ \." To achieve
predefined character class: \d meaning: represents 0 to 9 digits, two numbers are included, equivalent to [0-9] For example: The match rule is "\d", then the match is a number
predefined character class: \w meaning: The letter or number or underscore (the word character), equivalent to [a-za-z_0-9] For example: The match rule is "\w", then the match is a letter or a number or a slide line
Boundary match: ^ meaning: Represents the beginning of the line for example: The match rule is ^[abc][0-9]$, then the matching content starts at [ABC], which is equivalent to the left double quotation mark
boundary match: $ meaning: Represents the end of the line for example: The match rule is ^[abc][0-9]$, then the matching content needs to end with [0-9], which is equivalent to the right double quotation mark
boundary match: \b Meaning: The word boundary is represented for example: the match rule is "\b[abc]\b", then it represents the right and left side of the letter A or B or C need non-word characters ([a-za-z_0-9])
Quantity Word: X? meaning: X appears once or once or no for example: the match rule is "A?", then the content that needs to match is a character a, or a has no
Quantity Word: x* meaning: X appears 0 or more times for example: the match rule is "A *", then the content that needs to match is more than a character a, or a is not
Quantity Word: x+ meaning: X appears one or more times for example: the match rule is "A +", then the content that needs to be matched is more than one character a, or a
quantity Word: x{n} meaning: It means that X appears exactly n times for example: the match rule is "a{5}", then the content that needs to match is 5 characters a
quantity Word: x{n,} meaning: X appears at least n times for example: the match rule is "a{5,}", then the content that needs to match is at least 5 characters a
quantity Word: x{n,m} meaning: Represents X appears at least n times, but not more than m times for example: the match rule is "a{5,8}", then the content that needs to match is 5 characters A to 8 characters a
Regular expression rule-matching exercises

Please write a string that satisfies the following matching rules:

Rule: "[0-9]{6,12}"

What this rule needs to match is a number that is 6 to 12 bits in length. For example, use the data "123456789" to match the result to true; Use data "12345" to match the result to false.

Rule: "1[34578][0-9]{9}"

What the rule needs to match is a 11-digit mobile phone number, a 1th digit of 1, a 2nd digit of 3, 4, 5, 7, 8, and an arbitrary number from 9 to 0 after 9 bits.

For example, use the data "12345678901" to match the result to false; Use data "13312345678" to match the result to true.

Rule: "A*b"

The rule needs to match: There is a b;b after multiple A or 0 A that must be the last character.

For example, use the data "Aaaaab" to match the result to true; Use the data "ABC" to match the result to false.

Common methods in string classes involving regular expressions

public boolean matches (string regex)//Determines whether a string matches a given rule

Example: Check the QQ number.

1: The requirement must be 5-15 digits

2:0 cannot begin

Code Demo:

String QQ = "604154942"= "[1-9][0-9]{4,14}"; boolean Flag2 = qq.matches (regex);

Example: Verifying a mobile phone number

1: Required for 11 digits

2: The 1th bit is 1, the 2nd bit is 3, 4, 5, 7, 8, and the next 9 bits are any number between 0 and 9.

Code Demo:

String phone = "18800022116"= "1[34578][0-9]{9}"; boolean flag = phone.matches (regex);

Public string[] Split (string regex)//split This string according to the matching rule for the given regular expression

Example: Splitting a number in a string

Code Demo:
String s = "18-22-40-65"= "-"="=" "=" = ""= S.split (regex);

public string ReplaceAll (string regex,string Replacement)//replace the string contents of the rule with the new string

Example: replacing numbers in text with *

Code Demo:

String s = "hello12345world6789012"= "[0-9]"= S.replaceall (Regex, "*");
Regular expression Exercises

Match the correct number, match the rule:

Match positive integer: "\\d+"

Match positive decimals: "\\d+\\.\\d+"

Match negative integer: "-\\d+"

Match negative decimals: "-\\d+\\.\\d+"

Match a positive number that retains two decimal places: "\\d+\\.\\d{2}"

Match a positive number that retains 1-3 decimal places: "\\d+\\.\\d{1,3}"

Match a legitimate mailbox, matching rule:

"[A-za-z_0-9][email protected][a-za-z_0-9]+ (\\.[ a-za-z_0-9]+) + "

"\\[email protected]\\w+ (\\.\\w+) +"

Gets the number of each segment in the IP address (192.168.1.100) that matches the rule:

”\\.”

Date

The class Date represents a specific instantaneous, accurate to milliseconds.

Continue to look at the description of the date class and find that date has more than one constructor, except that it is partially obsolete, but that there are non-obsolete constructors that convert millisecond values to date objects.

// creates a Date object that turns the current millisecond value into a Date object New Date (1607616000000L); SYSTEM.OUT.PRINTLN (date); // Print Result: Fri Dec 00:00:00 CST 2020

But the millisecond value into a date, the format of the output is not good for us to read, continue to consult Api,date in the getyear, Getmouth and other methods, they are outdated, continue to look down, see the ToString method.

Click the ToString () method lookup, originally printed on the Date object is the default call this tostring method, and under this method also let us see the toLocaleString method, point in, this method is obsolete, starting from JDK 1.1, from the Dateformat.format (date date) instead. Now that this method is replaced by the Dateformat.format (date date), you need to consult the DateFormat class.

Common methods for date classes

Converts a Date object to a corresponding time millisecond value

  New Date ();  L=date.gettime ();  System.out.println (l);

0 points in milliseconds, time origin; January 1, 1970 CE, Midnight 0:00:00 UK Greenwich millisecond value is 0

System.currenttimemillis () return value long type parameter, used to get the millisecond value of the current date, must depend on the millisecond value

DateFormat

DateFormat is an abstract class of date/time formatting subclasses that formats and resolves dates or times in a language-independent manner. Date/time formatting subclasses (such as the SimpleDateFormat Class) allow formatting (that is, date-and text), parsing (text-to-date), and normalization.

We use this class to help us finish the conversion between the date and the text.

Continue reading Api,dateformat to help you format and resolve dates for any locale. For months, weeks, and even calendar formats (lunar and Gregorian), their code is completely unrelated to the conventions of the locale.

Date format

To format a date in the current locale, that is, the date and text, you do this by using the following method. DateFormat is an abstract class, and we need to use its subclass SimpleDateFormat to create objects.

Construction method

DateFormat class method

Code Demo:

// creates a date formatting object that you can specify when you get a formatted object New SimpleDateFormat ("Yyyy-mm-dd"); // to format a date New Date (1607616000000L= Df.format (date); System.out.println (str_time); // December 11, 2020

The DateFormat class works by converting a Date object to a string that matches the specified format, or converting a string that conforms to a specified format to a Date object.

Specify the format of the specific rules we can refer to the description of the SimpleDateFormat class, here to do a brief introduction, the rule is in a string, the following letters will be replaced with the corresponding time components, the remaining content is output as:

    • When y is present, y is replaced by the adult
    • When M is present, M is replaced with a month
    • When D is present, D is replaced with Rewardcash octopus
    • When H is present, the H is replaced with
    • When M is present, the M is replaced by the component
    • When S is present, S is replaced with seconds
Common methods of DateFormat class

The format method, which is used to convert a Date object to a string

The parse method, which is used to convert a string to date (the string is to conform to the specified format, otherwise it cannot be converted).

Code Demo:

Practice One: Convert a Date object to a string

New Date (1607616000000L); // Fri Dec 00:00:00 CST 2020 New  = Df.format (date); // the contents of STR are December 11, 2020

Exercise two: Convert a string to a Date object

String str =new= df.parse (str); // the contents of the Date object are Fri Dec 00:00:00 CST 2020
Calendar

The Calendar class, which appears after date, replaces many of the date's methods. This class encapsulates all possible time information into static member variables for easy access.

Calendar is an abstract class, because of language sensitivity, the Calendar class is not created directly when the object is created, but is created by a static method, processing the language-sensitive content, and then returning the subclass object, as follows:

Calendar class static method

Calendar C = calendar.getinstance (); Return Current time

Calendar class Common methods

public static Calendar getinstance ()//Get Date Object

public int get (int field)//Get Time field value, field see Help documentation

Year

month, starting from 0, Max 11, 0 for January, 11 for December.

DATE Day

When HOUR

Minute min

Second sec

Code Demo:

Calendar C = calendar.getinstance (); int year = c.get(calendar.year);

public void Add (int field,int amount)//Specify field to increment a value

Code Demo:

Calendar C = calendar.getinstance (); // Modify the current time to 3 days later  3); // Modify the current time to 5 hours later  5);

Public final void Set (int field,int value)//Set the value of the specified field

Code Demo:

Calendar C = calendar.getinstance (); // set Time is May 20, 2020 c. Set 2020 ); c. Set 4 ); c. Set );

Public final Date GetTime ()//Gets the date object to which the Calendar object was converted

Code Demo:

Calendar c == C.gettime ();

Precautions

    • The beginning of the Western week is Sunday, China is Monday.
    • In the Calendar class, the month representation is represented by 0-11 for January-December.
    • The date is the size of the relationship, the time depends on, the greater the time.
Date related classes Exercises

Find out how many days you've been born

Code implementation:

  Public Static voidMain (string[] args) {Calendar my=calendar.getinstance (); Calendar C=calendar.getinstance ();//Set Birth date 1995-05-10My.Set(Calendar.year,1995); My.Set(Calendar.month,4); My.Set(Calendar.date,Ten);//get the number of days in a time        intDay = c.Get(calendar.date); intMyday = My.Get(calendar.date); System. out. println (Day-myday); }

Find out how many days it's been today from January 1, 2020

Code implementation:

  Public Static voidMain (string[] args) {Calendar my=calendar.getinstance (); Calendar C=calendar.getinstance ();//Set Month Day 2020-01-01My.Set(Calendar.year,2020); My.Set(Calendar.month,0); My.Set(Calendar.date,1);//get the number of days in a time        intDay = c.Get(calendar.date); intMyday = My.Get(calendar.date); System. out. println (Myday-Day ); }

Java Basic Learning Note 13 Regular expressions for common APIs, Date, DateFormat, Calendar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.