我需要从字符串中提取以下模式,并根据输入返回一个可能的匹配。
通过不同的可能性,我使用了正则表达式,但我没有得到预期的结果:
输入a): 71346 G249 USD 70045620 27/08/2020 001 / 004
输入b): 71346 G249 USD 70045620/2020 27/08/2020 001 / 004
试一次
String result = data.replaceFirst ( "(.*?([0-9]{6,}\\/[0-9]{4}).*)|(.*?([0-9]{6,}).*)", "$1" );试二
String result = data.replaceFirst ( ".*?([0-9]{6,}\\/[0-9]{4})|([0-9]{6,}).*", "$1" );试三
String result = data.replaceFirst ( ".*?([0-9]{6,})([0-9]{6,}\\/[0-9]{4}).*", "$1" );根据投入的预期结果:
输入a): 70045620
输入b): 70045620/2020
发布于 2020-12-17 10:40:35
通过这种方式使用与捕获组的交替方式将根据数据给出不同的组号。如果需要替换中的单个组,则可以将第二部分设为可选部分。
String[] strings = {
"71346 G249 USD 70045620 27/08/2020 001 / 004",
"71346 G249 USD 70045620/2020 27/08/2020 001 / 004"
};
String regex = "^.*?\\b([0-9]{6,}(?:/[0-9]{4})?)\\b.*$";
for (String s : strings) {
System.out.println(s.replaceFirst(regex, "$1"));
}输出
70045620
70045620/2020您也可以找到匹配,而不是使用replaceFirst。
\b[0-9]{6,}(?:/[0-9]{4})?例如
String[] strings = {
"71346 G249 USD 70045620 27/08/2020 001 / 004",
"71346 G249 USD 70045620/2020 27/08/2020 001 / 004"
};
String regex = "\\b[0-9]{6,}(?:/[0-9]{4})?";
Pattern pattern = Pattern.compile(regex);
for (String s : strings) {
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(0));
}
}见另一个Java演示
输出
70045620
70045620/2020发布于 2020-12-17 02:35:40
我在这里使用String#replaceAll来处理这个问题,如下所示:
String[] inputs = { "71346 G249 USD 70045620 27/08/2020 001 / 004",
"71346 G249 USD 70045620/2020 27/08/2020 001 / 004" };
for (String input : inputs) {
String match = input.replaceAll(".*\\b(\\d{8}(?:/\\d{4})?)\\b.*", "$1");
System.out.println(input + " => " + match);
}这些指纹:
71346 G249 USD 70045620 27/08/2020 001 / 004 => 70045620
71346 G249 USD 70045620/2020 27/08/2020 001 / 004 => 70045620/2020发布于 2020-12-17 02:40:38
就我个人而言,我会避免在这方面使用regex。好像你只想要第四个词。类似于string.split()的东西可能会很好:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
String text = "71346 G249 USD 70045620 27/08/2020 001 / 004";
String result = text.split(" ")[3];
System.out.print(result);
}
}上面的程序将输出:70045620用于第一个输入,70045620/2020用于第二个输入。
https://stackoverflow.com/questions/65333862
复制相似问题