我对Java中使用的正则表达式不太了解。 如果我有一个字符串this/is/a/file!/path
正则表达式在java中,使搜索特定的字符串模式?
substring
现在
和indexOf
我能找到其间的出现和/
的!
名的文件,但我敢肯定这样的任务必须是使用正则表达式容易得多。
有人可以给我一个使用正则表达式这样做的例子吗?
我对Java中使用的正则表达式不太了解。 如果我有一个字符串this/is/a/file!/path
正则表达式在java中,使搜索特定的字符串模式?
substring
现在
和indexOf
我能找到其间的出现和/
的!
名的文件,但我敢肯定这样的任务必须是使用正则表达式容易得多。
有人可以给我一个使用正则表达式这样做的例子吗?
另一种方法是使用模式和匹配器。在这里,您可以使用组和更复杂的操作
Pattern pattern = Pattern.compile(yourRegex);
Matcher matcher = pattern.matcher(yourText);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
在
匹配器请看:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html
模式:http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
正则表达式中的Java:http://docs.oracle.com/javase/tutorial/essential/regex/
在Java中使用它们的最简单的方法是使用String.matches
方法:
boolean matches = "abc".matches("[a-z]+");
这将产生true
。
如果您必须多次使用特定的正则表达式模式,第二种方法很有用。你可以编译并重复使用:
Pattern pattern = Pattern.compile("[a-z]+");
Matcher matcher = pattern.matcher("abc");
boolean matches = matcher.matches();
String.matches只会匹配整个字符串。该问题涉及提取路径的匹配子字符串。 – 2012-01-12 10:42:52
财产以后为.*/([^!]*)!.*
应该这样做......那么你可以使用一个匹配找到第一组(括号之间的部分,第0组是整个匹配)
我没有测试这个解决方案...
您可以创建一个具有正则表达式的模式对象,然后从它创建一个匹配器对象到pa rse你的字符串。
String regex = ".*/(.*)!";
Pattern p = Pattern.compile (regex);
Matcher m = p.matcher(StringToBeMatched);
if (m.find()) {
String filename = m.group (1);
}
你没有测试这个解决方案,是吗?该代码是正确的,但该正则表达式甚至不会编译。 – 2012-01-12 11:47:28
纠正了正则表达式 – 2012-01-12 15:46:29
对于这个问题,你的方法是最简单又是最快的。除非你想读取除了字符串的'file'部分之外的东西,否则不要考虑RegEx。 – adarshr 2012-01-12 10:39:41
Google是你的朋友。 http://docs.oracle.com/javase/tutorial/essential/regex/ – 2012-01-12 10:40:14
@adarshr,感谢您的评论;) – Johnydep 2012-01-12 10:50:51