java - How to use regex to replace the string -


in java language,

how use regular expression deal string

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

and replace part of random(1,9) real random number between 1 9?

so basically, result string $.store.book[3].title or $.store.book[5].title

anybody can me?

using regular expression capture arbitrary numbers (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 utility method:

online demo 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

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -