正则表达式的^$

^表示匹配的字符串以什么开头,在[]中表示取反

$表示匹配的字符串以什么结尾

例子(修改自百度知道答案:https://zhidao.baidu.com/question/584158903311222605.html):

//以一个数字加上一个/多个任意字母/数字开头并且以一个数字加上一个/多个任意字母/数字结尾的正则表达式 
regex = "^d[da-zA-Z]+$";
input = "5dd";
System.out.println (input.matches (regex));
//输出:true // 以零个/多个任意字符加上一个/多个数字结尾的正则表达式,但不管开头是什么字符,只要结尾能匹配上那就是true
regex = ".*d+$";
input = "---===5";
System.out.println (input.matches (regex));
//输出:true

//
以一个/多个数字加上零个/多个任意字符开头的正则表达式,但不管结尾是什么字符,只要开头能匹配上那就是true
regex = "^d+.*";
input = "5dd---==-=";
System.out.println (input.matches (regex));
//输出:true

 另外,^$还可以用于限制一段中文的边界,如:

^.{3,10}$将匹配任意字符长度在3-10,包含中文。

而.{3,10}也能做到,但不能包含中文,只能匹配英文单词边界。

原文地址:https://www.cnblogs.com/hihtml5/p/6025837.html