【发布时间】:2016-08-22 18:37:36
【问题描述】:
我有一个字符串:
String s = "msqlsum81pv 0 0 25 25 25 2 -sn D:\\workdir\\PV 81\\config\\sum81pv.pwf -C 5000";
我想从此字符串中获取路径(在本例中为 D:\\workdir\\PV 81\\config\\sum81pv.pwf)。此路径是命令选项-sn 或-n 的参数,因此此路径始终出现在这些选项之后。
路径可能包含也可能不包含需要处理的空格。
public class TestClass {
public static void main(String[] args) {
String path;
String s = "msqlsum81pv 0 0 25 25 25 2 -sn D:\\workdir\\PV 81\\config\\sum81pv.pwf -C 5000";
path = s.replaceAll(".*(-sn|-n) \"?([^ ]*)?", "$2");
System.out.println("Path: " + path);
}
}
当前输出:Path: D:\workdir\PV 81\config\sum81pv.pwf -C 5000
预期输出:Path: D:\workdir\PV 81\config\sum81pv.pwf
Below Answers 适用于较早的情况。
i need a regex which return `*.pwf` path if the option is `-sn, -n, -s, -s -n, or without -s or -n.`
但如果我有以下情况,那么查找密码文件的正则表达式是什么。
String s1 = msqllab91 0 0 1 50 50 60 /mti/root/bin/msqlora -n "tmp/my.pwf" -s
String s2 = msqllab92 0 0 1 50 50 60 /mti/root/bin/msqlora -s -n /mti/root/my.pwf
String s3 = msqllab93 0 0 1 50 50 60 msqlora -s -n "/mti/root/my.pwf" -C 10000
String s4 = msqllab94 0 0 1 50 50 60 msqlora.exe -sn /mti/root/my.pwf
String s5 = msqllab95 0 0 1 50 50 60 msqlora.exe -sn "/mti/root"/my.pwf
String s6 = msqllab96 0 0 1 50 50 60 msqlora.exe -sn"/mti/root"/my.pwf
String s7 = msqllab97 0 0 1 50 50 60 "/mti/root/bin/msqlora" -s -n /mti/root/my.pwf -s
String s8 = msqllab98 0 0 1 50 50 60 /mti/root/bin/msqlora -s
String s9 = msqllab99 0 0 1 50 50 60 /mti/root/bin/msqlora -s -n /mti/root/my.NOTpwf -s -n /mti/root/my.pwf
String s10 = msqllab90 0 0 1 50 50 60 /mti/root/bin/msqlora -sn /mti/root/my.NOTpwf -sn /mti/root/my.pwf
String s11 = msqllab901 0 0 1 50 50 60 /mti/root/bin/msqlora
String s12 = msqllab902 0 0 1 50 50 60 /mti/root/msqlora-n NOTmy.pwf
String s13 = msqllab903 0 0 1 50 50 60 /mti/root/msqlora-n.exe NOTmy.pwf
如果选项是-sn, -n, -s, -s -n, or without -s or -n.,我需要一个返回*.pwf 路径的正则表达式
路径仅包含 *.pwf 文件扩展名,而不是 NOTpwf 或任何其他扩展名,并且代码应该除了最后两个之外都可以工作,因为它是无效命令。
注意:我已经问过此类问题,但没有按照我的要求进行任何操作。 (How to get specific substring with option vale using java)
【问题讨论】:
-
在不知道可能的字符串格式的情况下,这是一项非常困难的任务。此外,这些命令中的路径通常用双引号括起来。
-
你可以使用:[A-Z]:.*\.\w+ regex101.com/r/aE2aR7/5
-
@WiktorStribiżew:- 谢谢,字符串格式与上面相同。我只需要从此配置字符串中获取 .pdf 文件路径,并且此密码文件是命令选项 -sn 或 -n 的参数。
-
@TimBiegeleisen:为什么,你总是可以提出一些建议。我只知道在不知道上下文的情况下很难匹配带有空格的路径。如果 OP 确认之前总是有
-sn,之后总是有-C,那么-s?n\s*(.*?)\s*-C\b就可以了。更好 --s?n\s*(.*?)\s*-C\s+\d+$. -
@WiktorStribiżew:是的,总是有 -sn 或 -n 之前和 -C 之后。或路径可能包含空白或空白空白