0

I can have this string as below :

String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

or

String s = "chapterId=c_1&sectionId=s_24666";

I need to get the number ("24666" in the examples).

String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks

5
  • 2
    You could do a similar indexOf trick for the &. Commented Oct 7, 2014 at 6:32
  • You could solve this with regex.. Commented Oct 7, 2014 at 6:35
  • 2
    I believe the stars (*) are not part of the string, the user just wanted to make it bold but that wiki formatting doesn't work in code sections. Commented Oct 7, 2014 at 6:37
  • +1 icza :) @TheLostMind I don't know to work with regex very well :( Can you help me please? Commented Oct 7, 2014 at 6:39
  • @user3796867 - added an answer with regex :) Commented Oct 7, 2014 at 7:01

7 Answers 7

1

You can use regExp

    String s = "chapterId=c_1&sectionId=s_24666";
    //OR
    //String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
    s=s.replaceAll(".*?s_(\\d+).*","$1");
    System.out.println(s);

OUTPUT:

24666

Where,

  1. .*?s_ means anything before s_ (s_ inclusive)
  2. (\\d+) means one or more digits () used for group
  3. $1 means group 1 which is digits after s_

Note:Assumed that your every string follows specific format which includes s_ and number after s_.

Sign up to request clarification or add additional context in comments.

Comments

1

You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.

Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:

String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

String[] params = s.split("&");
for (String param : params) {
    String[] nameValue = param.split("=");

    if ("sectionId".equals(nameValue[0])) {
        int number = Integer.parseInt(nameValue[1].substring(2));
        System.out.println(number); // Prints 24666

        // If you don't care about other parameters, this will skip the rest:
        break;
    }
}

Note:

You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:

try {
    int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
    // Invalid parameter value, not the expected format!
}

Comments

0

Try this:

I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.

Code:

    String s = "chapterId=c_1&sectionId=s_**24666**";
    int endIndex = s.indexOf("&isHL");
    String answer = s.substring(s.lastIndexOf("s_") + 2,    endIndex == -1 ? s.length() : endIndex);

Comments

0

Try following:

  String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
  String tok[]=s.split("&");
  for(String test:tok){
      if(test.contains("s_")){
          String next[]=test.split("s_");
            System.out.println(next[1]);

      }
  }

Output :

24666

Alternatively you can simply remove all other words if they are not required as below

String s="chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);

Output :

24666

The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.

Comments

0

You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.

demo here

Comments

0

Following code will work even if there is multiple occurrence of integer in given string

   String inputString = "chapterId=c_a&sectionId=s_24666&isHL=1&cssFileName=haynes_45";

    String[] inputParams = inputString.split("&");
    for (String param : inputParams)
    {
        String[] nameValue = param.split("=");

        try {
            int number = Integer.parseInt(getStringInt(nameValue[1]));
            System.out.println(number); 
        }
        catch(IllegalStateException illegalStateException){                
        }                
    }


private String getStringInt(String inputString)
{
    Pattern onlyInt = Pattern.compile("\\d+");
    Matcher matcher = onlyInt.matcher(inputString);
    matcher.find();
    String inputInt = matcher.group();
    return inputInt;
}

OUTPUT

2466 1 45

Comments

-1

Use split method as

String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");

Now to get your desire number you just need to do

String finalResult = result3[1];

INPUT :

String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";

OUPUT :

24666

2 Comments

I've edited, I don't have **, I tried to bold them but I end up with those characters..
I've changed my answer. Please look at that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.