Comment diviser une chaîne en Java

Mots clés : javastringsplitjava

meilleur 5 Réponses Comment diviser une chaîne en Java

vote vote

92

String string = "004-034556"; String[] parts = string.split("-"); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556 
String[] parts = string.split(Pattern.quote(".")); // Split on period. 
if (string.contains("-")) {     // Split it. } else {     throw new IllegalArgumentException("String " + string + " does not contain -"); } 
String string = "004-034556"; String[] parts = string.split("(?<=-)"); String part1 = parts[0]; // 004- String part2 = parts[1]; // 034556 
String string = "004-034556"; String[] parts = string.split("(?=-)"); String part1 = parts[0]; // 004 String part2 = parts[1]; // -034556 
String string = "004-034556-42"; String[] parts = string.split("-", 2); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556-42 
vote vote

86

import java.util.regex.Pattern; import java.util.regex.Matcher;  class SplitExample {     private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");      public static void checkString(String s)     {         Matcher m = twopart.matcher(s);         if (m.matches()) {             System.out.println(s + " matches; first part is " + m.group(1) +                                ", second part is " + m.group(2) + ".");         } else {             System.out.println(s + " does not match.");         }     }      public static void main(String[] args) {         checkString("123-4567");         checkString("foo-bar");         checkString("123-");         checkString("-4567");         checkString("123-4567-890");     } } 
(\d+)-(\d+) 
([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters  ([^-]+)-([^-]+)            // Each part consists of characters other than - ([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,                            // the second consists of digits 
vote vote

75

String[] result = yourString.split("-"); if (result.length != 2)       throw new IllegalArgumentException("String not in correct format"); 
vote vote

67

String[] out = string.split("-"); 
vote vote

54

// This leaves the regexes issue out of question // But we must remember that each character in the Delimiter String is treated // like a single delimiter          public static String[] SplitUsingTokenizer(String subject, String delimiters) {    StringTokenizer strTkn = new StringTokenizer(subject, delimiters);    ArrayList<String> arrLis = new ArrayList<String>(subject.length());     while(strTkn.hasMoreTokens())       arrLis.add(strTkn.nextToken());     return arrLis.toArray(new String[0]); } 

Questions similaires