简体   繁体   English

从Java中的字符串中提取特定字符串

[英]Extract Particular String from string in java

I have a string like : String test = "A1=CA2=BOA2=RA4=OA11=O"; 我有一个像这样的字符串: String test = "A1=CA2=BOA2=RA4=OA11=O";
Now I want output like that : A1,A2,A2,A4,A11 现在我想要这样的输出: A1,A2,A2,A4,A11

If my string like : 如果我的字符串像:

String test = "[HEADER_1] [DATA] \n A10=T,(\"Re-N RO-25 M-N P-N (B)\"),1.0:0.8,R=25.0 F-7.829215,-4.032765 A20=B,R2,M=XY,R=29.999999999999996 F564.997550,669.454680";


public static void main(String[] args) {
    String test = "A1=CA2=BOA2=RA4=O";
    String data[] = test.split("[A-a]\\d{1,100}=");

    for (String str : data) {
      System.out.println("Split data:"+str);
    }      
}

What would be the regex for that? 正则表达式是什么?

I would not use split for that. 我不会为此使用split。 The regex for the parts that you want is /a\\d+/i . 您想要的零件的正则表达式是/a\\d+/i If you use this and the Solution from Create array of regex matches to collect all matches in a list, you can easily create the desired output. 如果使用此方法,并且“从正则表达式创建数组”中的“解决方案”在列表中收集所有匹配项,则可以轻松创建所需的输出。

Converted the Regex in Java-Parlor: 在Java-Parlor中转换了正则表达式:

public static void main(String[] args) {
    String test = "A1=CA2=BOA2=RA4=OA11=O";
    List<String> allMatches = new ArrayList<String>();
    Matcher m = Pattern.compile("(a\\d+)", Pattern.CASE_INSENSITIVE).matcher(test);

    while (m.find()) {
       allMatches.add(m.group());
    }
}

allMatches now contains A1 A2 A2 A4 A11 allMatches现在包含A1 A2 A2 A4 A11

The regex you are probably looking for is [Aa][0-9]{1,2} . 您可能正在寻找的正则表达式是[Aa][0-9]{1,2}

So in Java, 所以在Java中

import java.util.regex.Matcher;
import java.util.regex.Pattern;


String test = "A1=CA2=BOA2=RA4=OA11=O";
Matcher m = Pattern.compile("[A-a][0-9]{1,2}").matcher(test);
while (m.find()) {
    System.out.print(m.group(0)+",");
}
String test = "A1=CA2=BOA2=RA4=OA11=O";
String[] parts = test.split("=");
String[] output = new String[parts.length];
for (int i=0; i < parts.length; ++i) {
    output[i] = parts[i].replaceAll("^.*(A\\d*)$", "$1");
    System.out.println(parts[i] + " becomes " + output[i]);
}

Output: 输出:

A1 becomes A1
CA2 becomes A2
BOA2 becomes A2
RA4 becomes A4
OA11 becomes A11
O becomes O

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM