在java语言中,
如何使用正则表达式处理字符串
$.store.book[Random(1,9)].title
并将Random(1,9)
的部分替换为1
到9
之间的实际随机数?
所以基本上,结果字符串会像$.store.book[3].title
或$.store.book[5].title
有谁可以帮助我?
答案 0 :(得分:5)
我能想到的最简单的方法是使用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);
示例输出为:
$.store.book[7].title
答案 1 :(得分:2)
您必须分三步完成此操作。
首先,您必须找到“Random(1,9)”字符串。您可以使用带捕获组的正则表达式来解析值范围。请参阅http://docs.oracle.com/javase/tutorial/essential/regex/groups.html。
接下来,您必须生成随机数。
最后,您可以使用String.replaceFirst
将字符串替换为您生成的数字。
如果您想支持每个字符串多次出现,请重复此操作,直到没有任何字符串为止。
编辑:也就是说,如果您的范围总是 1到9,那么Jlewis071的答案就足够而且直截了当。
答案 2 :(得分:2)
使用正则表达式捕获任意数字(请参见 online demo ):
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 );
示例输出:
Input: $.store.book[Random(1,9)].title
Output: $.store.book[6].title
Online demo代码如下。
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"));
}
示例输出:
(1,9): $.store.book[4].title
(1,999): $.store.book[247].title
(50,200): $.store.book[71].title
答案 3 :(得分: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);
}
我可能搞砸了正则表达式......我看到acdcjunior刚刚发布了所有内容,完成了一个在线IDE来验证它。所以我会发布我的答案,所以人们都很感激我的努力!但是他的回答肯定是没有错误的,并且沿着相同的路线:)然后再次,我的确会在整个字符串中重复替换,正如其他答案所示。
答案 4 :(得分:0)
尝试使用String.replace();
符合您要求的示例:
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