hichkas
hichkas

Reputation: 43

substring starting with a char and following with digits in java

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

Upvotes: 0

Views: 46

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

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)

$r123
$r34563478

Upvotes: 1

Related Questions