How can I check is strings with characters that are not letters or number

I am trying to trim any characters that are before a-Z 0-9

but this doesn't work

I need >&%Hell$o to become Hell$o

private String removeStartingCharacters(String linkName) {
    if(linkName.startsWith("^[a-Z0-9]")){
        try {
            linkName = linkName.substring(1);               
        } catch (Exception e) {
            e.printStackTrace();
            return linkName;
        }
        return removeStartingCharacters(linkName);
    }else 
        return linkName;
}
Jon Skeet
people
quotationmark

I think this is what you're after:

public class Test {
    public static void main(String[] args) {
        System.out.println(trimStart("&%Hell$o"));
        // [ and ] are between A-Z and a-z...
        System.out.println(trimStart("[]Hell$o"));
        System.out.println(trimStart("Hell$o"));
    }

    private static String trimStart(String input) {
        // The initial ^ matches only at the start of the string
        // The [^A-Za-z0-9] matches all characters *except* A-Z, a-z, 0-9
        // The + matches at least one character. (The output is the same
        // as using * in this case, as if there's nothing to replace it would
        // just replace the empty string with itself...)
        return input.replaceAll("^[^A-Za-z0-9]+", "");
    }
}

(The output shows Hell$o in all cases.)

A single call to replaceAll is significantly simpler than what you're doing at the moment.

EDIT: replaceFirst will work too, but you do still need the ^ at the start to make sure it only replaces characters from the start of the string. The "first" in replaceFirst just means the first occurrence of the pattern, not the first characters within the input string. Use whichever method you find more readable.

Note that this only allows a-z, A-Z and 0-9 as your starting characters:

  • It doesn't allow the characters between Z and a (e.g. [ and ])
  • It doesn't allow non-ASCII letters or digits

You'll need to adjust the regex if those rules don't match your actual requirements

people

See more on this question at Stackoverflow