查找文件中出现的每个string并将其存储在List中



我正在编写一个程序,它将在文件中找到每一个纹理名称的出现,然后将其名称存储在列表中。比如说,我有一个文本文件,它的字符串是这样的:

{"sampletext";urlDistortion";textures/noissiannoise_10x .png";sampletext" urlnoise_wispy_dense .png";;urlGradient";textures/gradients/sparks.png";blendMode";sampletext";;urlMask";;textures/shader_test/FX_Radial_Grad.png"}

每个纹理名称都以"textures开头,然后以引号结束,例如"textures/gradients/sparks.png"

现在我想提取文件名并将其存储在一个列表中,所以从第一个出现的"textures/noise/FX_GaussianNoise_10x.png"我只会得到这个&;fx_gaussiannoise_10x .png&;部分。我有了一个想法,我将创建一个模式,将找到"纹理",跳过位置,并以某种方式复制其余的文件名部分。

try {
File file;
Pattern p = Pattern.compile("textures/");
List <String> textureNames = new ArrayList<>();
for (File f : list) {
file= f.getAbsoluteFile();
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Matcher matcher = p.matcher(line);
while (matcher.find()){
//and here i would like to add this texture name to my list and 
continue searching for the next occurence
}
System.out.println("found " +count);
}
}
}

我知道在Matcher类中有一个start()方法,它返回前一个匹配的开始索引,所以我可以在while循环中做这样的事情

String s = line.substring(matcher.start(),)

然后把这个添加到列表中,但是我不知道怎么指定endIndex

如果有人知道我该怎么做,或者如果有更好的方法来实现这一点,我会很感激的帮助。

下面是一个简单的测试用例,展示了您的内部循环的想法:

@Test
public void testParse() {
String line = "{"sampletext":"urlDistortion":"textures/Noises/FX_GaussianNoise_10x.png","sample text sample text "url":"textures/shader/shader_test/FX_Noise_Wispy_Dense.png","urlGradient":"textures/gradients/sparks.png","blendMode": "sample text","urlMask":"textures/shader_test/FX_Radial_Grad.png"}";
Pattern p = Pattern.compile(""(textures/[^\"]*)"");
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println("found " + m.group(1));
}
}

输出如下:

found textures/Noises/FX_GaussianNoise_10x.png
found textures/shader/shader_test/FX_Noise_Wispy_Dense.png
found textures/gradients/sparks.png
found textures/shader_test/FX_Radial_Grad.png

相关内容

最新更新