5

First time I use Regex statement.

I have java regex statement, which split String by pattern with list of some characters.

String line = "F01T8B02S00003H04Z05C0.12500";
Pattern pattern = Pattern.compile("([BCFHSTZ])");
String[] commands = pattern.split(line);

for (String command : commands) {
 System.out.print(command);
}

output of above code is like (018020000304050.12500)

Actually I want output like this, ("F", "01", "T", "8", "B", "02", "S", "00003", "H", "04", "Z", "05", "C", "0.12500").

Means desired output is contains pattern character and split value both.

Can you please suggest me?

Bhavin S.
  • 77
  • 12

3 Answers3

3

I've created a sample, try it and let me know if it's what you want.

public class Main {

public static void main(String[] args) {

    String line = "F01T8B02S00003H04Z05C0.12500";
    String pattern = "([A-Z][a-z]*)(((?=[A-Z][a-z]*|$))|\\d+(\\.\\d+)?)";

    Pattern r = Pattern.compile(pattern);

    Matcher m = r.matcher(line);
    HashMap<String, String> mHash = new LinkedHashMap<>();

    while (m.find()) {
        mHash.put(m.group(1), m.group(2));
    }

    System.out.println(mHash.toString());

}

}

Output is:

F 01
T 8
B 02
S 00003
H 04
Z 05
C 0.12500

Edit with LinkedHashMap

public class Main {

    public static void main(String[] args) {

        String line = "F01T8B02S00003H04Z05C0.12500";
        String pattern = "([A-Z][a-z]*)(((?=[A-Z][a-z]*|$))|\\d+(\\.\\d+)?)";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(line);
        HashMap<String, String> mHash = new LinkedHashMap<>();

        while (m.find()) {
            mHash.put(m.group(1), m.group(2));
        }

        System.out.println(mHash.toString());

    }
}

Output is :

{F=01, T=8, B=02, S=00003, H=04, Z=05, C=0.12500}

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
2

You can use a String#split on [A-Z] which keeps the delimiter as separated item:

String line = "F01T8B02S00003H04Z05C0.12500";
String[] result = line.split("((?<=[A-Z])|(?=[A-Z]))");

System.out.println(java.util.Arrays.toString(result));

Which will result in the String-array:

[F, 01, T, 8, B, 02, S, 00003, H, 04, Z, 05, C, 0.12500]

Try it online.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
0

Above all answer were correct. I got solution by below code also.

String line = "F01T8B02S00003H04Z05C0.12500A03";

String[] commands = line.split("(?<=[BCFHSTZ])|(?=[BCFHSTZ])");

for (String str: commands) {
    System.out.print(str);
}

Thanks all for help.

Bhavin S.
  • 77
  • 12