regex 正则表达式删除驱动器号

k4ymrczo  于 2023-06-30  发布在  其他
关注(0)|答案(4)|浏览(63)

我正在检查字符串中是否有letter后跟colon
如果是这样,则将两者都剥离。
F:/users/mark/ => /users/mark/
这是我到目前为止所拥有的:

if(Pattern.matches("[a-zA-Z]:", path))
        path = path.substring(2);

有没有人有更好的主意如何实现这一点?

luaexgnf

luaexgnf1#

您可以用途:

path = path.replaceAll("^[a-zA-Z]:", "");
os8fio9y

os8fio9y2#

您可以使用regex ^[^\/]*(.*)并捕获第一个组。

sourceString = sourceString.replaceAll("^[^\\/]*(.*)", "$1");

DEMO

输入

F:/users/mark/

匹配信息

MATCH 1
1.  [2-14]  `/users/mark/`
d4so4syb

d4so4syb3#

你可以通过简单的字符串方法来实现你的目标:

String path = "F:/some/path";
if (path.length() > 1 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':') {
    path = path.substring(2);
    System.out.println(path); // this is for demo
}

参见Java demo
其中:

  • path.length() > 1-如果path长度大于1
  • && Character.isLetter(path.charAt(0))-第一个字符是字母
  • && path.charAt(1) == ':'-并且第二个字符是:
  • path.substring(2)-使用从第二个索引开始的子字符串。

是的,不要忘记将结果赋给变量。

2cmtqfgy

2cmtqfgy4#

有点晚了,但我想我应该把对我有用的东西加进去。

String path = "F:\\some\\path";
if(path.matches("^[a-zA-Z]:.*"))  //checks for drive letter and colon
     path = path.split(":")[1];   //get everything after colon

相关问题