substring starting with a char and following with digits in java


Please briefly explain why you feel this question should be reported .

Report Cancel

How can I get the substring start with “$r” char following with digits and continue until the last digit. For example for the following strings I want these outputs:

example1: “helloeveryone$r123Stack(overflow24)” -> output:$r123

example2: “dskjlu h5678kjjklds($r34563478jlsd)sdjks%6jkj” -> output:$r34563478

solved 0
1 Answer 9 views 0

Answer ( 1 )

    December 15, 2016 at 7:04 am

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    You could use a regular expression with String.replaceAll(String, String) on a literal $r followed by one or more digits. Something like,

    String[] arr = { "helloeveryone$r123Stack(overflow24)", 
            "dskjlu h5678kjjklds($r34563478jlsd)sdjks%6jkj" };
    for (String str : arr) {
        System.out.println(str.replaceAll(".*(\$r\d+).*", "$1"));

    Output is (as requested)

    Best answer

Leave an answer


What is the capital of Egypt ? ( Cairo )

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>