1.程序判断用户从键盘输入的字符序列是否所有由英文字母所组成。java
import java.util.Scanner;
public class Example {
public static void main (String args[ ]) {
String regex = "[a-zZ-Z]+";
Scanner scanner = new Scanner(System.in);
System.out.println("输入一行文本(输入#结束程序):");
String str = scanner.nextLine();
while(str!=null) {
if(str.matches(regex))
System.out.println(str+"中的字符都是英文字母");
else
System.out.println(str+"中含有非英文字母");
System.out.println("输入一行文本(输入#结束程序):");
str = scanner.nextLine();
if(str.startsWith("#"))
System.exit(0);
}
}
}git
2.字符串的分解正则表达式
public String[] split(String regex)数组
字符串调用该方法时,使用参数指定的正则表达式regex做为分隔标记分解出其中的单词,并将分解出的单词存放在字符串数组中。网站
例:若要分解出所有由数字字符组成的单词,就必须用非数字字符串作分隔标记,spa
String regex=“\\D+”;//正则表达式对象
String digitword[]=str.split(regex);字符串
3.模式匹配input
例1:查找一个字符串中所有的单词monkeys以及该单词在字符串中的位置it
import java.util.regex.*;
public class Example {
public static void main(String args[ ]){
Pattern p; //模式对象
Matcher m;//匹配对象
String input=
"Have 7 monkeys on the tree, walk 2 monkeys, still leave how many monkeys?";
p=Pattern.compile("monkeys"); //初始化模式对象
m=p.matcher(input); //初始化匹配对象
while(m.find()){
String str=m.group();
System.out.println("从"+m.start()+"至"+m.end()+"是"+str);
}
}
}
例2:使用模式匹配查找一个字符串中的网址,而后将网址串所有剔除获得一个新字符串。
import java.util.regex.*; public class Example { public static void main(String args[ ]) { Pattern p; //模式对象 Matcher m; //匹配对象 String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+"; p = Pattern.compile(regex); //初试化模式对象 String s = "新浪:www.sina.cn,央视:http://www.cctv.com"; m = p.matcher(s); //获得检索s的匹配对象m while(m.find()) { String str = m.group(); System.out.println(str); } System.out.println("剔除网站地址后:"); String result = m.replaceAll(""); System.out.println(result); } }