假设我有一个正在运行的系统,我可以用一个正则表达式和一个替换字符串来参数化,以检查一些字符串,并将它的一部分与正则表达式匹配为零。
在内部,系统将标准Java特性用于regex,并且不会发生变化(不使用其他方法或类):
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class Main
{ // args[0]= "sample 066666 33 more text" -- will be read from database and is neither subject to change
// args[1]= "(\\d{0,9}\\d)([ _-])([3-9][0-9])"
// args[2]= "$1-$3"
public static void main (String[]args)
{
Pattern pattern = Pattern.compile (args[1]);
Matcher matcher = pattern.matcher (args[0]);
if (matcher.find ())
{
System.out.println (matcher.replaceFirst (args[2]));
// prints 'sample 066666-33 more text'
// but should be 'sample 0000066666-33 more text'
}
}
}它只是关于如何定义传递给main()的正则表达式和替换字符串,以便a)向左填充匹配部分,最多10位数字,以及b)替换不同的分隔符,如空格或_默认分隔符-
(上下文:它不是我的应用程序,所以我不能更改代码,只需在这里为这个特定用例提供这两个参数1和2的配置。在其他情况下,输入和正则表达式可能完全不同,从而得到完全不同的结果。这就像使用特定正则表达式为特定用例/结果参数化通用组件一样)
arg的示例
abc 1-31 def
abc 02 31 def
abc 55555_32 def
abc 066666 33 def
this value 1010101010-34 is what it should be like应该会导致
abc 0000000001-31 def
abc 0000000002-32 def
abc 0000055555-32 def
abc 0000066666-33 def
this value 1010101010-34 is what it should be like我成功地匹配了他们
(\d{0,9}\d)([ _-])([3-9][0-9]),但我找不到一种方法来在分隔符之前使用带零的左填充来精确定位10个数字,而字符串中可能包含正确的左填充数字,或者由于手动输入前导零但不能填充最多10个数字。
我找到了一个使用字典的解决方案,但没有真正设法使用,因为我不能扩展输入(args),但希望将字典添加到regex?https://stackoverflow.com/a/48891673/16110438中。
我见过其他解决方案,比如拥有多个捕获组
(\d{9})|...|(\d{2})|(\d)使用替换,例如
(?{1}$1)(?{2}$2)(?{3}$3)但同样,它不能与填充一起工作,我不太理解'?{1}‘真正代表什么。
你对我有什么建议吗?这在一个正则表达式执行中是可能的吗?
谢谢。
发布于 2021-06-04 17:11:37
你可以在String#format,String#replaceAll和String#replace的帮助下做到这一点。
演示:
public class Main {
public static void main(String[] args) {
String [] arr = {
"1-31",
"02#31",
"55555-32",
"066666/33",
"999999999 34",
"1010101010-35"
};
for(String s: arr) {
String formatted = String.format("%13s", s.replaceAll("[#/\\s]", "-")).replace(' ', '0');
System.out.println(formatted);
}
}
}输出:
0000000001-31
0000000002-31
0000055555-32
0000066666-33
0999999999-34
1010101010-35发布于 2021-06-04 18:31:18
替代方案:
使用的正则表达式:
"(\\d{10})\\D+(\\d+)"上下文中的正则表达式:
public static void main(String[] args) {
String input = "1-31\n"
+ "02#31\n"
+ "55555-32\n"
+ "066666/33\n"
+ "999999999 34\n"
+ "1010101010-35";
String paddedInput = Pattern.compile("^", Pattern.MULTILINE).matcher(input).replaceAll("0".repeat(9));
Matcher matcher = Pattern.compile("(\\d{10})\\D+(\\d+)", Pattern.MULTILINE).matcher(paddedInput);
while(matcher.find()) { // adjusting the padding and numbers in group 1 to a total of 10 digits
System.out.printf("%s-%s%n", matcher.group(1), matcher.group(2));
}
}输出:
0000000001-31
0000000002-31
0000055555-32
0000066666-33
0999999999-34
1010101010-35https://stackoverflow.com/questions/67813056
复制相似问题