字符串startswith DRIVELETTER:\

时间:2013-05-29 14:59:55

标签: java string startswith

Java String.startsWith()中的快速问题需要某种通配符。

我需要查看链接是以http://还是本地驱动器(c:\d:\等)开头,但我不知道驱动器号。

所以我觉得我需要像myString.startsWith("?:\\")

这样的东西

有什么想法吗?

干杯

为此欢呼,但我想我需要在此基础上继续努力。

我现在需要迎合

1.http://
2.ftp://
3.file:///
4.c:\
5.\\

它有点矫枉过正,但我​​们想确保我们已经抓住了所有这些。

我有

if(!link.toLowerCase().matches("^[a-z]+:[\\/]+.*")) {

适用于任何字符或字符,后跟:(例如http:,ftp:,C:),其中包含1-4但我无法满足\\

我能得到的最近的是(这可行,但在regEx中获得它会很好。)

if(!link.toLowerCase().startsWith("\\") && !link.toLowerCase().matches("^[a-z]+:[\\/]+.*")) {

3 个答案:

答案 0 :(得分:5)

startsWith

不支持regular expression
^[a-zA-Z]:\\\\.*

^   ^     ^    ^
|   |     |    |
|   |     |    everything is accepted after the drive letter
|   |    the backslash (must be escaped in regex and in string itself)
|  a letter between A-Z (upper and lowercase)
start of the line

然后您可以使用yourString.matches("^[a-zA-Z]:\\\\")

答案 1 :(得分:2)

您应该使用正则表达式。

Pattern p = Pattern.compile("^(http|[a-z]):");
Matcher m = p.matcher(str);
if(m.find()) {
   // do your stuff
}

答案 2 :(得分:1)

String toCheck = ... // your String
if (toCheck.startsWith("http://")) {
   // starts with http://
} else if (toCheck.matches("^[a-zA-Z]:\\\\.*$")) {
    // is a drive letter
} else {
    // neither http:// nor drive letter
}