为什么这段代码的输出只有xyz?

「已注销」 2013-04-18 02:42:24
String str = "abc\nijk\nxyz\n";
Pattern p = Pattern.compile(".*\\n$");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
}
...全文
1871 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ddplayer12 2013-04-18
  • 打赏
  • 举报
回复

import java.util.regex.*;

public class Test02 {
	public static void main(String[] args){
		String str = "abc\nijk\nxyz\n";
		Pattern p = Pattern.compile(".*\\n$?");
		Matcher m = p.matcher(str);
		while (m.find()) {
			System.out.println(m.group());
		}
	}	
}
正则最后加个?也可以,先让字符吃掉匹配的
ddplayer12 2013-04-18
  • 打赏
  • 举报
回复

import java.util.regex.*;

public class Test02 {
	public static void main(String[] args){
		String str = "abc\nijk\nxyz\n";
		Pattern p = Pattern.compile(".*\\n");
		Matcher m = p.matcher(str);
		while (m.find()) {
			System.out.println(m.group());
		}
	}	
}
输出:

abc

ijk

xyz
由于你的代码里的正则有$,$是整个字符串结尾的意思。
  • 打赏
  • 举报
回复
改为Pattern p = Pattern.compile(".*\\n"); String str = "abc\nijk\nxyz\n";//这里的\n是换行了,表示 abc ijk xyz .*\\n$当然只匹配最后一个了
loveofmylife 2013-04-18
  • 打赏
  • 举报
回复
.匹配除换行符以外的任意字符

62,621

社区成员

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

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