一个正则表达式的问题,求助

sdu_badboy 2011-08-15 03:32:04
package regex;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Regex
{
//测试字符串是否满足正则表达式
static boolean test(String str, String reg)
{
Pattern p=null;
Matcher m=null;

boolean result=false;

p=Pattern.compile(reg);
m=p.matcher(str);

result=m.matches();

return result;
}

public static void main(String args[])
{
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print("请输入字符串:"); //输入15812341234
String strc=buffer.readLine();

System.out.print("请输入正则表达式:"); //[1][35]\\d{9}
String regex=buffer.readLine();

String strc2="15812341234";
String regex2="[1][35]\\d{9}";

System.out.println(test(strc,regex)); //(1)输出false,为什么????? System.out.println(test(strc2, regex2)); //(2)输出true
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

程序运行后,我在分别在控制台输入15812341234和[1][35]\\d{9},为什么(1)和(2)出的结果却截然不同?
个人感觉应该都是ture啊,这是为毛啊,为毛啊!!
...全文
74 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞跃颠峰 2011-08-15
  • 打赏
  • 举报
回复
[1][35]\d{9}这样才对
\\是在Java源代码中定义字符串才表示一个\符号
从控制台读入的时候只需要输入一个\
剑神一笑 2011-08-15
  • 打赏
  • 举报
回复
如1L说的 控制台输入只需要写[1][35]\d{9}
[Quote=引用 1 楼 shine333 的回复:]
\\是你编写java源代码的时候转义,代表一个\
你直接在控制台,或者文件中只需要一个\
System.out.print("请输入正则表达式:"); //[1][35]\d{9}
[/Quote]
shine333 2011-08-15
  • 打赏
  • 举报
回复
static boolean test(String str, String reg) {
System.out.println(reg);
System.out.println("[1][35]\\d{9}");
..
}
softroad 2011-08-15
  • 打赏
  • 举报
回复
buffer.readLine();可能包含空格或回车,输出看看了。
softroad 2011-08-15
  • 打赏
  • 举报
回复
String strc=buffer.readLine();
strc = strc.trim();
试试
shine333 2011-08-15
  • 打赏
  • 举报
回复
\\是你编写java源代码的时候转义,代表一个\
你直接在控制台,或者文件中只需要一个\
System.out.print("请输入正则表达式:"); //[1][35]\d{9}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧