gpt4 book ai didi

Java使用和使用正则表达式分割字符串

转载 作者:行者123 更新时间:2023-11-30 04:11:51 26 4
gpt4 key购买 nike

这似乎是一个基本的事情,但我似乎无法理解正则表达式,我以前从未真正使用过它们,现在我遇到了它们会很有用的时候。

我在过去的一个小时里查看了示例和过去的问题,但仍然不明白。我的问题是我有一个字符串

"(2 h 9 min from now) | +18.7 feet"

我想将其分成两个字符串

String a = "2 h 9 min from now";

String b = "18.7 feet";

如何使用正则表达式分割字符串并在其他字符串中使用“正则表达式”?

到目前为止我已经想出了:

stringx.split("(%s) | +%s \n");

stringx.split("(\\w) | +\d.\d feet");

但我不知道如何将 %s (如果那是正确的)放入正则表达式之外的字符串

最佳答案

当您想要删除一些字符(()+)时,最安全的方法是使用 Pattern 匹配标准正则表达式。和 Matcher类(class):

public static void main (String[] args) {
String input= "(2 h 9 min from now) | +18.7 feet";
System.out.println("Input: "+ input);
Pattern p = Pattern.compile("\\(([^)]+)\\) \\| \\+(\\d+\\.\\d feet)");
Matcher m = p.matcher(input);
String a = null, b = null;
if (m.find()) {
a = m.group(1);
b = m.group(2);
}
System.out.println("a: "+ a);
System.out.println("b: "+ b);
}

输出:

Input: (2 h 9 min from now) | +18.7 feet
a: 2 h 9 min from now
b: 18.7 feet

<强> See online demo here

关于Java使用和使用正则表达式分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19413588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com