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?
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
Pattern matcher() method in Java with examples The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With