gansub
gansub

Reputation: 1174

String regex for replacement

I have this pattern (N|S)(..)(W|E)(...).hgt. I need to replace this with (N|S)(..)(W|E)(...).xyz.hgt.

So as an example if I have N06E072.hgt I would need to replace this with N06E072.xyz.hgt. This is for a set of files where the values could change depending on latitude and longitude. The way I have coded this is to extract the latitude and the value and the corresponding longtitude and it's value. Concatenate the characters and then do a simple replace of these set of characters with the new set of characters. Is there a better way of doing this ?

private static final Pattern filePattern = Pattern.compile("(N|S)(..)(W|E)(...).*")
Matcher matcher = filePattern.matcher(file.getName());
    if (matcher.matches()) {
        String latDir = matcher.group(1);
        lat = Integer.parseInt(matcher.group(2));
        if (latDir.equalsIgnoreCase("s"))
            lat *= -1;
        String lonDir = matcher.group(3);
        lon = Integer.parseInt(matcher.group(4));
        if (lonDir.equalsIgnoreCase("w"))
            lon *= -1;
    }

Upvotes: 0

Views: 60

Answers (1)

halloei
halloei

Reputation: 2036

I'd do it like this:

String s = "N06E072.hgt".replaceAll("([NS]{1}.{2}[WE]{1}.{3})\\.(.{3})", "$1.xyz.$2");

Upvotes: 1

Related Questions