[英]How to use regex to replace the string
在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.