Nipun Joshi
Nipun Joshi

Reputation: 1

Retrieve a Sub-string from a string after the first occurrence of a character from a range of characters

i am trying to retrieve a sub-string from a string from the first occurence of any character between A-Z and a-z

for example:

if the string is 13BHO1234FO

then substring should be BHO1234FO

i.e the string from the first occurence of the character 'B'.

Upvotes: 0

Views: 71

Answers (3)

WJS
WJS

Reputation: 40062

Try this. It simply deletes the first part of the string you don't want and returns the rest. The original string is unchanged.

String[] testCases =
        { "13BHO1234FO", "ARSTOP123!", "133KSLK", "122222" };

for (String s : testCases) {
    String sub = s.replaceFirst("^[^A-Za-z]+", "");
    System.out.println("'" + sub + "'");
}

Prints substrings surrounded by single quotes to show the string.

'BHO1234FO'
'ARSTOP123!'
'KSLK'
''

Upvotes: 1

Alexey R.
Alexey R.

Reputation: 8686

Try this one:

public static void main(String[] args) {
    String test = "13BHO1234FO";
    System.out.println(test.replaceFirst("^.*?(?=[A-Za-z])", ""));
}

Upvotes: 0

Mobina
Mobina

Reputation: 7109

You can use a regex and Matcher to find the index of the first alphabetical character and make a substring starting from the index:

import java.util.regex.*;
class Main {
    public static void main(String[] args) {
        String text = "13BHO1234FO";
        Pattern pattern = Pattern.compile("[A-Za-z]");
        Matcher matcher = pattern.matcher(text);
        matcher.find();
        int index = matcher.start();
        String substr = text.substring(index);
        System.out.println(substr);
    }
}

Upvotes: 0

Related Questions