0

I have following String :

Test: Testid #123123 - Updated

I want to find the substring 123123 from this string.

I tried : <msg>.substring(15, 21); It gives me the correct result.

but I want to find this substring in the way that it should find the id between the # and the next space without giving the beginning and ending index.

Thanks.

7 Answers 7

2

Try this:

s.substring(s.indexOf("#")+1, s.indexOf(" ", s.indexOf("#")+1))

this gives you the string starting a the char after # until the next blank.

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

Comments

2

Try this,

String text = "Test: Testid #123123 - Updated";
int startIndex = text.indexOf('#'); //Finds the first occurrence of '#' 
int endIndex = text.indexOf(' ',startIndex); //Finds the first occurrence of space starting from position of # 
String subString = text.substring(startIndex+1, endIndex);
System.out.println(subString);

Or try to use regex

Comments

1

If your example is really as simple as the one you give, then you will not need to use regular expressions. However, if your real input is more complex, then the regular expression will be less onerous than trying to split the string in a clever way.

import java.util.regex.*;


public class Foo{
    public static void main(String[] args) {
        String original =  "Test: Testid #123123 - Updated";
            Pattern mypattern = Pattern.compile("#([0-9]*) ");
        Matcher matcher = mypattern.matcher(original);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Comments

0

Just split it with # then split the result with - you will get the correct result.

Comments

0

Have you tried int indexOf(int ch, int fromIndex) ? You can search for the next space from the given index.

http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

Comments

0

this might be helpful..

String temp="Test: Testid #123123 - Updated";
 int _first=temp.indexOf("#");
 int _last= temp.indexOf(" ", _first);
String result=temp.substring(_first, _last);

Comments

0

You can use following code to get the value between '#' and space.

String str = "Test: Testid #123123 - Updated";
str = str.substring(str.indexOf('#')+1, str.indexOf(' ', str.indexOf("#")+1)+1);

Comments

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.