1。
package com.yinbodotcc;
import java.util.Scanner;
import java.io.*;
import java.util.regex.*;
public class UserInput {
public static void main(String []args) throws Exception
{
///
//
Scanner sc=new Scanner(System.in);
//读取输入到第一个白格
System.out.println("please input you name: ");
System.out.printf("%s %n",sc.next());
//当做整数读取
System.out.println("please input you age: ");
System.out.printf("%s %n",sc.nextInt());
//从文件中读取
sc=new Scanner(new File("one.txt"));
while(sc.hasNextInt())//如果这碰到的是整数
{
int temp=sc.nextInt();
System.out.println(temp);
}
while(sc.hasNextLong())//如果这碰到的是浮点数
{
long temp=sc.nextLong();
System.out.println(temp);
}
while(sc.hasNext())//剩下的当做串读取
{
System.out.println(sc.next());
}
//当然Scanner类也有nextLine方法
//
/
/*
* 用正则表达式来做
*
*/
/*
* replaceAll用的就是正则表达式
* replace 没有使用正则表达式
* /
String str = "abcdefgabcabc";
System.out.println(str.replaceAll(".bc", "###"));
System.out.println(str.replace("ab", "x"));
System.out.println(str);
System.out.println("请输入西安某个电话号码");
Scanner sc2=new Scanner(System.in);
String callNum=sc2.next();
if(callNum.matches("029-[0-9]{8}"))
System.out.println("输入号码正确");
else System.out.println("电话号码不正确");
System.out.println("请输入移动手机号码");
String cellNum=sc2.next();
if(cellNum.matches("13[5-9][0-9]{8}"))
System.out.println("输入号码正确");
else System.out.println("电话号码不正确");
Scanner sc3=new Scanner(System.in);
System.out.print("輸入電子郵件: ");
String str = sc3.next();
String pa="^[_a-z0-9-]+([.][_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$";
Pattern p=Pattern.compile(pa);
Matcher m=p.matcher(str);
if(m.matches())
System.out.println("格式正確");
else
System.out.println("格式錯誤");
}
}
下面是一个用不同于白空的分隔符的例子
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("//s*fish//s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
输出为:
1
2
red
blue
提示:
String上的正則表示式,實際上是利用了Pattern與Matcher的功能,當您呼叫String的matches()
方法時,實際上是呼叫Pattern的靜態(static)方法matches(),這個方法會傳回boolean值,
表示字串是否符合正則表示式
2。查找匹配的
package com.yinbodotcc;
import java.util.regex.*;
public class UsePatternMatcher {
public static void main(String[] args) {
String phones1 =
"Justin's phone number: 555550939-100391/n" +
"momor's phone number: 0939-666888/n";
Pattern pattern = Pattern.compile(".*0939-//d{6}");
Matcher matcher = pattern.matcher(phones1);
while(matcher.find()) {
System.out.println(matcher.group());
}
String phones2 =
"caterpillar's phone number: 0952-600391/n" +
"bush's phone number: 0939-550391";
matcher = pattern.matcher(phones2);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
}
这样这其中部分的匹配,它也能打印