For example, in a B/S mode application that needs to be used for registration and login, it is necessary to verify the validity of the user registry form in the browser, but to prevent hacker, it must be verified on the server again.
Question: Check whether the email address is valid on the server side: You may write as follows:
public boolean checkEmailLegal(String temp){ //temp = "ddenfj#@fe_dw.comw"; return temp.matches("^([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");}
Of course, writing in this way can meet your needs, but today I want to share with you my usage experience on improving efficiency by using pattern. First, let's take a look at my simple tests on the surface code:
import java.util.regex.Pattern;public class SimpleTest {public static void main(String[] args){String temp = "ddenfj#@fe_dw.comw";int count = 1;long a = System.currentTimeMillis();for(int i=0;i<count;i++){temp.matches("^([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");}long b = System.currentTimeMillis();System.out.println(b-a);a = System.currentTimeMillis();Pattern emailPattern = Pattern.compile("^([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");for(int i=0;i<count;i++){emailPattern.matcher(temp).matches();}b = System.currentTimeMillis();System.out.println(b-a);}}
When the number of runs is 1, the running result is:
4
0
When the number of runs is 100, the running result is:
16
1
When the number of runs is 1000, the running result is:
111
8
When the number of runs is 10000, the running result is:
343
11
When the number of runs is 100000, the running result is:
841
65
When the number of runs is 10 million, the running result is:
8205
94
We know that to match a regular expression, we first create a finite automatic machine.
My conclusion: from the test notes, we can see that the string. the time of the matches () method does not mean linear growth. We can conclude that the JVM must be a string. the matches () method is cached. That is to say, all intermediate objects generated by calling this method are not cleared by JVM. If it is applied to your application, the efficiency may be obvious.
Bytes ----------------------------------------------------------------------------------------------------------
After writing the above content, I want to take a look at the source code of string. Matches:
public boolean matches(String regex) { return Pattern.matches(regex, this); }
public static boolean matches(String regex, CharSequence input) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); return m.matches(); }
It seems that my understanding of JVM is incorrect,
However, we can see from their source code that if we write pattern as a static property and use spring to manage objects, the efficiency will be improved a lot!
Hope you can join us!