正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。
许多程序设计语言都支持利用正则表达式进行字符串操作。例如,在Perl中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由Unix中的工具软件(例如sed和grep)普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、regexen。
题目描述:请实现一个函数用来匹配包括"和"的正则表达式,模式中的 '.' 表示任意一个字符,而''*"表示它前面的个字符可以出现任意次(包含0次)。在本题中,匹配是指所有字符串的所有字符匹配整个模式,例如,字符串"aaa"与模式''a.a''和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配。
public class Solution{
public boolean match(char [ ] str,char[ ] pattern){
String a =new String (str);//把字符数组转换成字符串,通过构造函数
String regex =new String(pattern);
return a.matches(regex);
}
}
常用正则表达式如下:
package 正则表达式;
import java.util.regex.Pattern;
import java.security.acl.Group;
import java.util.regex.Matcher;
import org.junit.Test;
public class Regxtest {
/**
* 正则表达式的最常用范例
*/
@Test
public void test1() {
System.out.println("Hello!I'm Laurence.May you have a good luck!");
}
@Test
public void test2() {
String regx = "\\d{11}";// 在字符串中要表示一个\转义字符,就要用两个\\匹配11 位整数
String string = "12345678911";
System.out.println(string.matches(regx));
}
/**
*
*
*
*/
@Test
public void test3() {
String regx = "hello";// 匹配的字符串里面要包含hello
String str = "hello";
System.out.println(str.matches(regx));
}
@Test
public void test4() {
String regx = "[abcdefgh]ello";// 该规则表示匹配abcdefgh中的任意一个字母。一次只匹配一个字母
String str = "e";
System.out.println(str.matches(regx));
}
@Test
public void test5() {
String regx = "[a-zA-Z0-9]ello";// 该规则表示进匹配
String str = "hello";
System.out.println(str.matches(regx));
str = "aello";
System.out.println(str.matches(regx));
str = "2ello";
System.out.println(str.matches(regx));
}
@Test
public void test6() {
String regx = "[a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]o";
String str = "hello";
System.out.println(str.matches(regx));
str = "aello";
System.out.println(str.matches(regx));
str = "2ello";
System.out.println(str.matches(regx));
}
/**
* +:匹配1-多次
*/
@Test
public void test7() {
String regx = "[a-zA-Z0-9+XZZCV]+";
String str = "hello";
System.out.println(str.matches(regx));
str = "aello";
System.out.println(str.matches(regx));
str = "2ello";
System.out.println(str.matches(regx));
}
/*
* *匹配0-多次(一个字符没有也匹配)
*
*
*/
public void test8() {
String regx = "[a-zA-Z0-9]*";
String str = "hello";
System.out.println(str.matches(regx));
str = "aello";
System.out.println(str.matches(regx));
str = "2ello";
System.out.println(str.matches(regx));
}
/*
* ? 匹配0-1次(没有是可以的)
*
*
*/
public void test9() {
String regx = "[a-zA-Z0-9]?";
String str = "hello";
System.out.println(str.matches(regx));
str = "aello";
System.out.println(str.matches(regx));
str