使用正则表达式在java中提取子字符串

我需要从字符串中提取"URPlus1_S2_3"

 "Last one: http://abc.imp/Basic2#URPlus1_S2_3," 

在Java语言中使用正则表达式。

有人可以帮帮我吗? 我是第一次使用正则表达式。

尝试

 Pattern p = Pattern.compile("#([^,]*)"); Matcher m = p.matcher(myString); if (m.find()) { doSomethingWith(m.group(1)); // The matched substring } 
 String s = "Last one: http://abc.imp/Basic2#URPlus1_S2_3,"; Matcher m = Pattern.compile("(URPlus1_S2_3)").matcher(s); if (m.find()) System.out.println(m.group(1)); 

你必须学习如何指定你的要求;)

您还没有真正定义用于查找该字符串的标准,但这里有一种基于’#’分隔符的方法。 您可以根据需要调整正则表达式。

 expr: .*#([^,]*) extract: \1 

到这里获取语法文档:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

 String s = Last one: http://abc.imp/Basic2#URPlus1_S2_3," String result = s.replaceAll(".*#", ""); 

如果没有“#”,上面的内容将返回完整的String。 使用正则表达式有更好的方法,但这里最好的解决方案是不使用正则表达式。 有工作的URL和URI类。

由于这是你第一次使用正则表达式,我建议采用另一种方式,现在更容易理解(直到你掌握正则表达式;)如果你需要:它将很容易修改:

 String yourPart = new String().split("#")[1]; 

这是一个 很长的版本:

 String url = "http://abc.imp/Basic2#URPlus1_S2_3,"; String anchor = null; String ps = "#(.+),"; Pattern p = Pattern.compile(ps); Matcher m = p.matcher(url); if (m.matches()) { anchor = m.group(1); } 

要理解的要点是使用括号,它们用于创建可以从模式中提取的组。 在Matcher对象中, group方法将从索引1开始按顺序返回它们,而索引0返回完全匹配。

如果您只想要#之后的所有内容,请使用split:

 String s = "Last one: http://abc.imp/Basic2#URPlus1_S2_3," ; System.out.println(s.split("#")[1]); 

或者 ,如果要解析URI并获取片段组件,则可以执行以下操作:

 URI u = new URI("http://abc.imp/Basic2#URPlus1_S2_3,"); System.out.println(u.getFragment());