发表于: 2018-01-17 21:21:57
1 603
今天完成的事
学习了一下正则表达式
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by ${MIND-ZR} on 2018/1/16.
*/
public class test1 {
public static void main(String[] args) {
Pattern pattern=Pattern.compile("ab",Pattern.CASE_INSENSITIVE);
Matcher matcher=pattern.matcher("ABcabdAb");
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
// using Pattern split() method
pattern = Pattern.compile("\\W");
String[] words = pattern.split("one@two#three:four$five");
for (String s : words) {
System.out.println("Split using Pattern.split(): " + s);
}
// using Matcher.replaceFirst() and replaceAll() methods
pattern = Pattern.compile("1*2");
matcher = pattern.matcher("11234512678");
System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
}
}
还有另一种
import java.math.BigInteger;
/**
* Created by ${MIND-ZR} on 2018/1/16.
*/
public class test2 {
public static void main(String[] args) {
Long mobilephone=12345678910L;
String mobilePhoneReg = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
if (!mobilephone.matches(mobilePhoneReg)) {
System.out.println("手机号码格式不正确!");
return false;
}
}
}
收获
正则表达式定义了字符串的模式。正则表达式可以用来搜索、编辑或处理文本。正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。Java正则表达式和Perl的是最为相似的。
Java正则表达式的类在 java.util.regex 包中,包括三个类:Pattern,Matcher 和PatternSyntaxException。
- Pattern对象是正则表达式的已编译版本。他没有任何公共构造器,我们通过传递一个正则表达式参数给公共静态方法 compile 来创建一个pattern对象。
- Matcher是用来匹配输入字符串和创建的 pattern 对象的正则引擎对象。这个类没有任何公共构造器,我们用patten对象的matcher方法,使用输入字符串作为参数来获得一个Matcher对象。然后使用matches方法,通过返回的布尔值判断输入字符串是否与正则匹配。
- 如果正则表达式语法不正确将抛出PatternSyntaxException异常。
遇到的问题
还是不熟悉
明天要做的事
正式开始敲代码了
评论