[英]Finding substring from a string using regex java
我有一个字符串:
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
以下答案在较早的情况下可以正常工作。
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
路径-sn, -n, -s, -s -n, or without -s or -n.
注意:我已经问过这种类型的问题,但是按照我的要求没有任何工作。 ( 如何使用java使用选项vale获取特定的子字符串 )
尝试这个
String s = "msqlsum81pv 0 0 25 25 25 2 -sn D:\\workdir\\PV 81\\config\\sum81pv.pwf -C 5000";
int l=s.indexOf("-sn");
int l1=s.indexOf("-C");
System.out.println(s.substring(l+4,l1-2));
您也可以使用: [AZ]:.*\\.\\w+
与其使用复杂的正则表达式进行替换,不如建议一个更简单的匹配项 :
String s = "msqlsum81pv 0 0 25 25 25 2 -sn D:\\workdir\\PV 81\\config\\sum81pv.pwf -C 5000";
Pattern pattern = Pattern.compile("\\s-s?n\\s*(.*?)\\s*-C\\s+\\d+$");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
System.out.println(matcher.group(1));
}
// => D:\workdir\PV 81\config\sum81pv.pwf
如果末尾的-C <NUMBER>
是可选的,则用可选的组-> (?:\\\\s*-C\\\\s+\\\\d+)?$
包装。
图案细节 :
\\\\s
空格 -s?n
一个-sn
或-n
(因为s?
匹配可选的s
) \\\\s*
-0+空格 (.*?)
-组1匹配除换行符以外的任何0+个字符 \\\\s*
-同上 -C
文字-C
\\\\s+
-1+空格 \\\\d+
-1个或更多数字 $
-字符串结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.