I am new to Regex and very confused why there get no groups returned by the split
method in the following operation:
String toSplit ="FN:Your Name";
String splitted [] = toSplit.split("(FN:)([A-Za-z]*) ([A-Za-z]*)");
System.out.println("Length: "+splitted.length);
Output: Length: 0
Question: What is the reason and how can I get Your
and Name
returned in the array?
You don't want to split but to use a Matcher :
String toSplit ="FN:Your Name";
Pattern pattern = Pattern.compile("(?:FN:)([A-Za-z]*) ([A-Za-z]*)");
Matcher matcher = pattern.matcher(toSplit);
if (matcher.find()) {
String[] splitted = new String[]{
matcher.group(1),
matcher.group(2)
};
System.out.println("splitted: " + Arrays.toString(splitted));
}
Result:
splitted: [Your, Name]
Small note: I've made the first group non capturing with ?:
because you don't need to get it in the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.