Question

Quick question in Java String.startsWith() which needs some sort of wildcard.

I need to check to see if a link starts with http:// or a local drive (c:\,d:\ etc) but I do not know the drive letter.

So I think I need something like myString.startsWith("?:\\")

Any ideas?

Cheers

Cheers for that, but think I need to build on this a little.

I now need to cater for

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

it's overkill but we want to be sure we've caught them all.

I have

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

which works for any character or characters followed by a : (example http:, ftp:, C:) which covers 1-4 but I can't cater for \\

The nearest I can get is this (which works, but it'd be nice to get it in the regEx).

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

Solution

You will need a regular expression, which is not supported by startsWith:

^[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

Then you can use yourString.matches("^[a-zA-Z]:\\\\")

OTHER TIPS

You should use regular expressions for this.

Pattern p = Pattern.compile("^(http|[a-z]):");
Matcher m = p.matcher(str);
if(m.find()) {
   // do your stuff
}
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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top