在java语言中,
如何使用正则表达式处理字符串
$.store.book[Random(1,9)].title
并将 的部分替换为之间的Random(1,9)
实随机数?1
9
所以基本上,结果字符串会喜欢$.store.book[3].title
或$.store.book[5].title
有谁能帮助我吗?
我能想到的最简单的方法是使用 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
您必须分三个步骤完成此操作。
首先,您必须找到“Random(1,9)”字符串。您可以使用带有捕获组的正则表达式来解析值范围。请参阅http://docs.oracle.com/javase/tutorial/essential/regex/groups.html。
接下来,您必须生成随机数。
最后,您可以使用String.replaceFirst
生成的数字替换字符串。
如果您想支持每个字符串多次出现,请重复此操作,直到没有剩余为止。
编辑:也就是说,如果您的范围始终是1 到 9,那么 Jlewis071 的答案就足够且直截了当。
使用正则表达式来捕获任意数字将是(请参阅此处的在线演示):
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
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
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 来验证它。所以无论如何我都会发布我的答案,让人们欣赏我的努力!但是他的答案肯定是没有错误的,并且沿着相同的思路:) 再说一次,我的确实在整个字符串中重复了替换,正如其他答案所建议的那样。
尝试使用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