java replaceall的一个问题

hssnankai 2012-07-16 09:28:46
String ss = "I am a student,I come from tianjin";
String Keywords = ss.replaceAll("I[^(come)]come","")
.replaceAll("tianjin", "");
System.out.println(Keywords);

我想从I匹配到come之前(一定是要检测在这个单词之前,单个字符不行),将从I到come的所有字符替换掉,然后再替换后面的tianjin,最后输出from,请问我这么写为什么不对?应该怎么写才行。非常感谢。
...全文
72 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
龙四 2012-07-17
  • 打赏
  • 举报
回复

String ss = "I am a student,I come from tianjin";
String keywords1 = ss.replaceAll("I[^I]*?come","");
System.out.println(keywords1);
String keywords2 = ss.replaceAll("I.*?come","");
System.out.println(keywords2);

龙四 2012-07-17
  • 打赏
  • 举报
回复

从I匹配到come之前
String ss = "I am a student,I come from tianjin";
你里面有两个I
是匹配红字部分吗

[Quote=引用楼主 的回复:]
String ss = "I am a student,I come from tianjin";
String Keywords = ss.replaceAll("I[^(come)]come","")
.replaceAll("tianjin", "");
System.out.println(Keywords);

我想从I匹配到come之前(一定是要检测在这个单词之前,单个字符不……
[/Quote]
龙四 2012-07-17
  • 打赏
  • 举报
回复
[^(from)]真的是你想的那个意思吗?
这是什么意思?
[^(from)]匹配一个字符,该字符不能是以下字符:(from

[Quote=引用 4 楼 的回复:]

2楼朋友,我就想从中提取出from,能不能设定一个终止单词。例如[^(from)]* 表示除了from这个单词以外其他的都匹配
[/Quote]
hssnankai 2012-07-17
  • 打赏
  • 举报
回复
2楼朋友,我就想从中提取出from,能不能设定一个终止单词。例如[^(from)]* 表示除了from这个单词以外其他的都匹配
hssnankai 2012-07-17
  • 打赏
  • 举报
回复
1楼朋友,那要是改成ss = "I really come from tianjin",那用你的表达式就没法提取出from
hssnankai 2012-07-17
  • 打赏
  • 举报
回复
哦,明白了。非常感谢。
龙四 2012-07-17
  • 打赏
  • 举报
回复
*
*?
两者都是修饰其前面的一个字符或整个括号,而不会作用于后面的字符


[Quote=引用 9 楼 的回复:]

*是贪婪匹配的,它会先一次性匹配到字符串的结尾,然后不断回溯
*?是非贪婪匹配的,它每往后匹配一个字符都会去看看后面的come满足不满足条件

如果我没记错的话应该是这样

引用 8 楼 的回复:

ticmy朋友,?come 就表示come这个字符串出现一次或0次吗?如果(come)?表示什么意思呢?这俩有什么区别吗?我验证过"I am a student,I come fro……
[/Quote]
龙四 2012-07-17
  • 打赏
  • 举报
回复
*是贪婪匹配的,它会先一次性匹配到字符串的结尾,然后不断回溯
*?是非贪婪匹配的,它每往后匹配一个字符都会去看看后面的come满足不满足条件

如果我没记错的话应该是这样

[Quote=引用 8 楼 的回复:]

ticmy朋友,?come 就表示come这个字符串出现一次或0次吗?如果(come)?表示什么意思呢?这俩有什么区别吗?我验证过"I am a student,I come from come tianjin"使用("I.*?come")就只是匹配到第一个come就结束了,?come 对.*做了限定嘛?
[/Quote]
hssnankai 2012-07-17
  • 打赏
  • 举报
回复
ticmy朋友,?come 就表示come这个字符串出现一次或0次吗?如果(come)?表示什么意思呢?这俩有什么区别吗?我验证过"I am a student,I come from come tianjin"使用("I.*?come")就只是匹配到第一个come就结束了,?come 对.*做了限定嘛?
龙四 2012-07-16
  • 打赏
  • 举报
回复
我表示没看懂
现在是什么结果?
你想要什么结果?
五哥 2012-07-16
  • 打赏
  • 举报
回复
Java code

public class Test10 {

public static void main(String []args){
String ss = "I am a student,I come from tianjin";
String Keywords = ss.replaceAll("I[^(come)]come","")
.replaceAll("tianjin", "");
System.out.println(Keywords);


}
}



结果:

I am a student, from

58,454

社区成员

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

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