Java implementation of string matching (based on regular)

There is a string. How to query whether there are y and f characters in it? The darkest way is:

Program 1: I know if, for statement and charat ()

It seems intuitive, but it is difficult to deal with complex work in this way. If you want to query a text, is there is is is? Whether there is something or Ting, etc. It's a nasty job.

Java for Java util. Regex package

According to the object-oriented idea, it is more natural to encapsulate the string you want to query, such as is, thing or Ting, into an object, and use this object as a template to match a text. The template is the regular expression discussed below. Let's not consider the complexity. Let's take an example: program 2: I don't understand. Can we have a look first?

If STR matches regex, the result is true, otherwise it is false. If you want to ignore case when searching, you can write:

Pattern p=Pattern. compile(regEx,Pattern.CASE_INSENSITIVE);

Although we don't know the details of pattern (template, pattern) and matcher (matcher) for the time being, the program feels better. If we first query is and then query thing or Ting, we only need to modify the template pattern instead of considering the if statement and for statement, or through charat().

1. Write a special string - regular expression, such as a|f.

2. Compile the regular expression into a template: P

3. Use the template p to match the string str.

Now let's see how Java handles it (Java programmers can't use these classes until JDK 1.4).

Pattern class and lookup

  ①public final class java. util. regex. Pattern is a compiled expression of regular expressions. The following statement creates a pattern object and assigns it to the handle P: pattern P = pattern compile(regEx);

Interestingly, the pattern class is final, and its constructor is private. Maybe someone tells you something about design patterns, or you check the information yourself. The conclusion here is that the pattern class cannot be inherited. We cannot create the object of the pattern class through new.

Therefore, in the pattern class, two overloaded static methods are provided, and their return value is the pattern object (reference of). For example:

Of course, we can declare the handle of the pattern class, such as pattern P = null;

② P. matcher (STR) refers to a matcher that uses the template p to generate a string STR, and its return value is a reference to the matcher class. Why do you want this? According to the natural idea, can't you return a Boolean value?

We can simply use the following methods:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>