Dan
Dan

Reputation: 51

How to use regex to replace the string

In java language,

How to use the regular expression to deal with the string

$.store.book[Random(1,9)].title

and replace the part of Random(1,9) to a real random number between 1 to 9?

So basically, the result string will like $.store.book[3].title or $.store.book[5].title

Anybody who can help me?

Upvotes: 2

Views: 200

Answers (5)

acdcjunior
acdcjunior

Reputation: 135752

Using a regular expression to capture arbitrary numbers would be (see online demo here):

String input= "$.store.book[Random(1,9)].title";
System.out.println("Input: "+ input);
Pattern p = Pattern.compile("(?<=\\[)Random\\((\\d+),(\\d+)\\)(?=\\])");
Matcher m = p.matcher(input);
String output = input;
if(m.find()) {
    int min = Integer.valueOf(m.group(1));
    int max = Integer.valueOf(m.group(2));
    int rand = min + (int)(Math.random() * ((max - min) + 1));
    output = output.substring(0, m.start()) + rand + output.substring(m.end());
}
System.out.println("Output: "+ output );

Example output:

Input: $.store.book[Random(1,9)].title
Output: $.store.book[6].title

As a utility method:

Online demo for code below.

public static String replaceRandom(String input) {
    Pattern p = Pattern.compile("(?<=\\[)Random\\((\\d+),(\\d+)\\)(?=\\])");
    Matcher m = p.matcher(input);
    String output = input;
    if (m.find()) {
        int min = Integer.valueOf(m.group(1));
        int max = Integer.valueOf(m.group(2));
        int rand = min + (int)(Math.random() * ((max - min) + 1));
        output = output.substring(0, m.start()) +rand+ output.substring(m.end());
    }
    return output;
}

public static void main(String[] args) {
    System.out.println("(1,9): "
                        + replaceRandom("$.store.book[Random(1,9)].title"));
    System.out.println("(1,999): "
                        + replaceRandom("$.store.book[Random(1,999)].title"));
    System.out.println("(50,200): "
                        + replaceRandom("$.store.book[Random(50,200)].title"));
}

Example output:

(1,9): $.store.book[4].title
(1,999): $.store.book[247].title
(50,200): $.store.book[71].title

Upvotes: 2

sdanzig
sdanzig

Reputation: 4500

Random rnd = new Random(System.currentTimeMillis())
Pattern pattern = Pattern.compile(".*Random\\((\\d+),(\\d+)\\).*");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    int min = matcher.group(1);
    int max = matcher.group(2);
    int newInt = rnd.nextInt(max-min+1) + min;
    str = str.replaceFirst("Random\\([^)]+\\)",String.valueOf(newInt));
    matcher = pattern.matcher(str);
}

And I probably messed up the regexes... and I see acdcjunior just posted it all, complete with an online IDE to verify it. So I'll post my answer anyway so people appreciate my effort! But his answer is error free for sure, and along the same lines :) Then again, mine does repeat the replacement throughout the entire string, as suggested by other answers.

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try using String.replace();

Example to suit your requirement:

   String data = "$.store.book[Random(1,9)].title";
    Random random = new Random();

    // Replace the sub-string
    String replacedData = data.replace("Random(1,9)", String.valueOf(random.nextInt() / 10000));
    System.out.println(replacedData); // after replacement 

Upvotes: 0

Jlewis071
Jlewis071

Reputation: 175

The easiest way I can think of would be using String.replace():

String str = "$.store.book[Random(1,9)].title";
str = str.replace("Random(1,9)", String.valueOf((int)(Math.random() * 9 + 1)));        
System.out.println(str);

Sample output being:

$.store.book[7].title

Upvotes: 5

Jason C
Jason C

Reputation: 40315

You will have to do this in three steps.

First you will have to find the "Random(1,9)" string. You can use a regular expression with capture groups to parse out the value range. See http://docs.oracle.com/javase/tutorial/essential/regex/groups.html.

Next you will have to generate your random number.

Finally you can use String.replaceFirst to replace the string with the number you've generated.

If you want to support multiple occurrences per string, repeat that until there are none left.

Edit: That said, if your range is always 1 to 9, Jlewis071's answer is sufficient and straightforward.

Upvotes: 2

Related Questions