2017-05-29 128 views
2

匹配行和提取文件名我有一个字符串以以下格式正则表达式在Java

Index: /aap/guru/asdte/atsAPI.tcl 
=================================================================== 
RCS file: /autons/atsAPI.tcl,v 
retrieving revision 1.41 

Index: /aap/guru/asdte/atsAPI1.tcl 
=================================================================== 
RCS file: /autons/atsAPI1.tcl,v 
retrieving revision 1.41 

我想要的是匹配行开始Index:,然后得到路径的文件名。

我的意思是先获得Index: /aap/guru/asdte/atsAPI.tcl,然后提取atsAPI.tcl作为最终结果。

目前我正在使用匹配两次,第一整行,然后提取文件名。

我的问题是,如何在java中的单个正则表达式中做到这一点。

当前的代码

String line = "Index: /aap/guru/asdte/atsAPI.tcl\r\n===================================================================\r\nRCS file: /autons/atsAPI.tcl,v\r\nretrieving revision 1.41\r\n\r\nIndex: /aap/guru/asdte/atsAPI1.tcl\r\n===================================================================\r\nRCS file: /autons/atsAPI1.tcl,v\r\nretrieving revision 1.41"; 
Pattern regex1 = Pattern.compile("Index:.*?\\n", Pattern.DOTALL); 
Pattern regex2 = Pattern.compile("[^*/]+$"); 

Matcher matcher1 = regex1.matcher(line); 
while (matcher1.find()) { 
    String s = matcher1.group(0); 

    Matcher matcher2 = regex2.matcher(s); 
    while (matcher2.find()) { 
     System.out.println(matcher2.group(0)); 
    } 
} 
+0

https://codebunk.com/b/128141613/ –

+0

你不需要'DOTALL'标志,它使你在你的不贪婪的点上添加一个换行符。 '.'默认与新行不匹配。 – revo

+0

@g_p我已经包括了如何使用一个正则表达式以及我的答案中的工作演示。希望能帮助到你! – degant

回答

1

如何做到这一点在一个普通在java中表达。

使用捕获组如下所示。 正则表达式:

^Index:.*\/(.*) 

现在的文件名可以通过使用matcher.group(1)来获得,并且由最后部分(.*)在正则表达式表示

  • ^比赛开始锚
  • Index:字面原样匹配是
  • .*匹配任何东西(贪婪)
  • \/比赛斜线/
  • (.*)在捕获组文件名

确保(?m)Pattern.MULTILINE标志设置,这样的匹配是多线的起始锚^在每一行的开头匹配匹配。

Regex101 Demo

编辑:修改代码,只使用一个正则表达式,像这样:

Pattern pattern = Pattern.compile("^Index:.*\\/(.*)", Pattern.MULTILINE); 

Matcher matcher = pattern.matcher(line); 
while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

// Output: 
atsAPI.tcl 
atsAPI1.tcl 

Demo

0

试试这个^Index.+\/([^\.]+\.\w+)$gm标志或Index.+\/([^\.]+\.\w+)没有m标志。唯一的捕获组是文件的名称。

0

试试下面的正则表达式,得到的答复是第一场比赛组:

Index:.*?\/([\w]+\.[\w]*) 

您可以通过以下链接进行调试: Regex link