java - Java parse string using regex into variables
问题描述
I need to extract variables from a string.
String format = "x:y";
String string = "Marty:McFly";
Then
String x = "Marty";
String y = "McFly";
but the format can be anything it could look like this y?x => McFly?Marty
How to solve this using regex?
Edit: current solution
String delimiter = format.replace(Y, "");
delimiter = delimiter.replaceAll(X, "");
delimiter = "\\"+delimiter;
String strings[] = string.split(delimiter);
String x;
String y;
if(format.startsWith(X)){
x = strings[0];
y = strings[1];
}else{
y = strings[0];
x = strings[1];
}
System.out.println(x);
System.out.println(y);
This works well, but I would prefer more clean solution.
解决方案
根本不需要正则表达式。
public static void main(String[] args) {
test("x:y", "Marty:McFly");
test("y?x", "McFly?Marty");
}
public static void test(String format, String input) {
if (format.length() != 3 || Character.isLetterOrDigit(format.charAt(1))
|| (format.charAt(0) != 'x' || format.charAt(2) != 'y') &&
(format.charAt(0) != 'y' || format.charAt(2) != 'x'))
throw new IllegalArgumentException("Invalid format: \"" + format + "\"");
int idx = input.indexOf(format.charAt(1));
if (idx == -1 || input.indexOf(format.charAt(1), idx + 1) != -1)
throw new IllegalArgumentException("Invalid input: \"" + input + "\"");
String x, y;
if (format.charAt(0) == 'x') {
x = input.substring(0, idx);
y = input.substring(idx + 1);
} else {
y = input.substring(0, idx);
x = input.substring(idx + 1);
}
System.out.println("x = " + x);
System.out.println("y = " + y);
}
输出
x = Marty
y = McFly
x = Marty
y = McFly
如果可以将格式字符串更改为正则表达式,那么使用命名捕获组将使其变得非常简单:
public static void main(String[] args) {
test("(?<x>.*?):(?<y>.*)", "Marty:McFly");
test("(?<y>.*?)\\?(?<x>.*)", "McFly?Marty");
}
public static void test(String regex, String input) {
Matcher m = Pattern.compile(regex).matcher(input);
if (! m.matches())
throw new IllegalArgumentException("Invalid input: \"" + input + "\"");
String x = m.group("x");
String y = m.group("y");
System.out.println("x = " + x);
System.out.println("y = " + y);
}
与上面相同的输出,包括值顺序。
推荐阅读
- stream - APIRTC:如何只记录选定的流?
- mysql - 如何配置没有响应的 mysql 数据库?
- html - 引导单选按钮组未正确显示
- ruby-on-rails - 无法在 macOS Catalina 上安装 Cocoapods
- android - (android) getAdapterPosition() 是否只能在 OnClick() 中工作?
- laravel - 我正在尝试使用 laravel 显示与用户相关的角色
- arrays - 将结构的第一个变量分配给另一个
- c# - 每次我运行我的代码时我都会遇到这个问题..这是我的代码
- python - 列表框不显示结果
- amazon-web-services - 无法在新的 AWS gRPC ELB 上建立不安全的 gRPC 连接