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 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 =;
        lat = Integer.parseInt(;
        if (latDir.equalsIgnoreCase("s"))
            lat *= -1;
        String lonDir =;
        lon = Integer.parseInt(;
        if (lonDir.equalsIgnoreCase("w"))
            lon *= -1;

Source: regex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.