djangofan
djangofan

Reputation: 29669

How to get a substring of a certain character followed by a number?

In Java, how would I get a substring of a certain character followed by a number?

The string looks like this:

To be, or not to be. (That is the question.) (243)

I want the substring up until the (243), where the number inside the parenthesis is always changing every time I call.

Upvotes: 0

Views: 580

Answers (6)

DukeMe
DukeMe

Reputation: 166

Using a regex this can be solved with.

public class RegExParser {

    public String getTextPart(String s) {

        String pattern = "^(\\D+)(\\s\\(\\d+\\))$";

        String part = s.replaceAll(pattern, "$1");
        return part;

    }
}

Simple and performance is good.

Upvotes: 0

i-bob
i-bob

Reputation: 423

Use a regular expression:

newstr = str.replaceFirst("\(\d+\)", "");

What this means is to find a substring beginning with (, then any number of digits, and then the character ). Then replace the substring with the empty string, "".

Reference: java.lang.String.replaceFirst()

Upvotes: 2

Tyler
Tyler

Reputation: 506

You could use a for loop and add the characters before the number to a separate string

String sentence = "To be, or not to be. (That is the question.) (243)";

public static void main(String[] args) {
    String subSentence = getSubsentence(sentence);
}

public String getSubsentence(String sentence) {
    String subSentence = "";
    boolean checkForNum = false;
    for (int i = 0; i < sentence.length(); i++) {
        if (checkForNum) {
            if (isInteger(sentence.getSubstring(i, i+1))) return subSentence;
            checkForNum = false;
        } else {
            if (sentence.getSubstring(i, i+1).equals("(")) checkForNum = true;
            else subSentence += sentence.getSubstring(i, i+1);
        }
    }
    return subSentence;
}

public boolean isInteger(String s) {
try { 
    Integer.parseInt(s); 
} catch(NumberFormatException e) { 
    return false; 
}
    return true;
}

Upvotes: 0

PurpleVermont
PurpleVermont

Reputation: 1241

I think you can actually just do something like:

mystring.substring(0,mystring.lastIndexOf"("))

assuming that the last thing on the line will be the number in parentheses.

Upvotes: 0

Keppil
Keppil

Reputation: 46219

You can use String.replaceAll():

String s = "To be, or not to be. (That is the question.) (243)";
String newString = s.replaceAll("\\(\\d+\\).*", "");

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57192

You could match it with a regex, and get the index of the regex. Then use that to get the index in the string.

An example of that is Can Java String.indexOf() handle a regular expression as a parameter?

Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.find()){
    System.out.println(matcher.start());//this will give you index
}

Upvotes: 0

Related Questions