2

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?

2
  • I've given you some hints below, but please post the code you have so far, describe the problem you are having with it, and tell us how you've tried to solve it. Commented Aug 13, 2013 at 3:52
  • Can Random(1,9) be other ranges? I missed that part if so... Commented Aug 13, 2013 at 3:53

5 Answers 5

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help,but i need to say the Random(1,9) is not invariable, The string should like "$.store.book[Random(a,b)].title",which a and b are different integer in every time.
gotcha, try to make that clear next time! in that case, I think @acdcjunior has what you need :)
2

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

Comments

2

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.

Comments

1
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.

Comments

0

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 

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.