2

Basically, I'm getting a file path from a string inside of a CSV file. However, for some reason, the program generating the CSV file removes the colon from the string, so I end up with a file path that does not work inside of Java. The typical output is /x/Rest/Of/Path where x is the drive letter, but may occasionally be x/ instead of /x/. Basically, I need to add a colon after the drive letter if there isn't one already; changing either /x/ or x/ to x:/. I'm sure this is mostly done through regex, but I'm still trying to figure out the basics of regex myself, so I'm not sure how to write it. Thanks in advance for any help.

4

1 回答 1

2

在这里,试试这个,并研究它以了解它是如何工作的:

String path = "/C/Rest/Of/Path";
Pattern p = Pattern.compile("^(/?[CDEFGH])/");
Matcher m = p.matcher(path);
String pathWithColon = m.replaceAll("$1:/");

这是一个指南:

  1. ^称为锚点。它匹配字符串的开头。没有它,这个正则表达式也会匹配/foo/C/Rest/Of/Path,我们不希望这样。
  2. 可以表示不同的?东西,具体取决于它出现的位置。如果它不紧跟开括号(,不紧跟量词 *, +, another ?, {n}, {m,n}, 不出现在字符类 []中,也没有转义\?,那么它是一个量词,意思是“0或前一个实体的 1 个,”在这种情况下,/. 将其视为“可选”运算符。
  3. [CDEFGH]称为字符类。它的意思是“这些字符中的任何一个”。你可以像这样否定一个字符类[^CDEFGH]:这将意味着,“任何一个字符,但不是这些。” 如果您想接受任何大写字母,则可以使用范围:[A-Z]。如果您想接受任何信件,那么:[a-zA-Z]
  4. 大多数正则表达式周围的括号称为捕获组捕获组。它“保存”了介于两者之间“捕获”的任何东西。
  5. $1更换时,您可以通过、$2、等引用“已保存”(捕获)的组$3。(因此,您可以捕获多个组;每个捕获组按其左括号的顺序编号。)在上面的示例中,请注意我也捕获了 the /?,因此如果存在斜线,那么它将存在于也输出,如果不是,则不是。

快乐学习!

编辑

我应该举例说明一种更简单的开始方法。我很抱歉。这也可以:

String path = "/C/Rest/Of/Path";
path = path.replaceAll("^(/?[CDEFGH])/", "$1:/");

使用编译模式只会提高效率。例如,如果您要替换一个包含 10,000 个路径的数组,您将编译一次模式,然后使用匹配器替换循环中的每个路径。(如果不编译,引擎最终不得不为遇到的每个路径从头开始解析模式。)

于 2013-04-30T20:21:44.547 回答