如何使用 JAVA 从大字符串中提取路径?

我找不到任何模式(算法)来从这种类型的长字符串中提取文件路径。

List<Person>newPersonList = new PersonUtility().getAllPerson(\"C://data//person.txt\");

我只需要以下路径:

C://data//person.txt


慕盖茨4494581
浏览 53回答 2
2回答

杨__羊羊

您可以使用正则表达式来提取路径:String str = "ListnewPersonList = new PersonUtility().getAllPerson (\"C://data//person.txt\")";Matcher m = Pattern.compile("\\w://[^\"]+").matcher(str);while(m.find()) {&nbsp; &nbsp; System.out.println(m.group());}输出:C://data//person.txt

qq_笑_17

ListNewPersonList 听起来像是您正在处理一个列表而不是一个大字符串?一般来说,类名应以大写字母开头,变量名应以小写字母开头。但我们假设你是正确的,并且我们在其他地方声明了String&nbsp;ListNewPersonList&nbsp;...好的,所以你有一个字符串。Java 有大量的方法固定在 String 上来操作它 - 甚至包括正则表达式(让 Perl 发挥作用的东西)。您可能正在寻找的是这样的:int&nbsp;x&nbsp;=&nbsp;ListNewPersonList.indexOf("C://");例如,查找您不会合理期望在文本中其他任何地方找到的子字符串。那么你所需要的只是一个结束索引,你可以这样做:&nbsp;String&nbsp;theFileNameToLookFor&nbsp;=&nbsp;ListNewPersonList.substring(x,&nbsp;y);或者可能是 y-1,具体取决于。对字符串边界要非常小心,因为底层实现默认将它们视为数组,并且您不想尝试对实际上不存在的数组部分进行索引。如果你这样做,Java 不会喜欢它。但这是问题所在 - 除非您确定要查找的特定文件结尾(在本例中为“.txt”),否则您会被塞满,因为您无法确定目录名称的长度。从长篇来看,答案可能如下所示:&nbsp;&nbsp;String&nbsp;answer&nbsp;=&nbsp;ListNewPersonList.substring( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ListNewPersonList.indexOf("C://"), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ListNewPersonList.indexOf(".txt"));当然,如果您碰巧有一个 .txt 出现在第一个 C:// 之前,那是非常不安全的这就是人生。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java