Java split method

I am trying to split an entered number like (123) 456-7890.

 String [] split = s.split(delimiters);

      

I've searched the internet for ways to delimit the scope code inside a set of parentheses, but I haven't found anything that worked for my case. I don't know if the array works with printing it. The array is not required, but I didnโ€™t know what else to do as it requires using the split method.

+3


source to share


4 answers


import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld{
    public static void main(String[] args){
        String phoneNumber = "(123)-456-7890";
        String pattern = "\\((\\d+)\\)-(\\d+)-(\\d+)";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(phoneNumber);
        if (m.find())
            System.out.println(m.group(1) + " " + m.group(2) + " " + m.group(3));
     }
}

      



You can try it here .

+1


source


If I understand your question, you can use Pattern

how (XXX) XXX-XXXX

, where X

is the number. You can also use {n}

to request n

. You are grouping ()

. Something like,

String str = "(123) 456-7890";
Pattern p = Pattern.compile("\\((\\d{3})\\) (\\d{3})-(\\d{4})");
Matcher m = p.matcher(str);
if (m.matches()) {
    String areaCode = m.group(1);
    String first3digits = m.group(2);
    String last4digits = m.group(3);
    System.out.printf("(%s) %s-%s%n", areaCode, first3digits,
            last4digits);
}

      

Gives your requested result

(123) 456-7890

      



or , if you must use split

, you can first delete (

and )

with a call replaceAll

and something like

String str = "(123) 456-7890";
String[] arr = str.replaceAll("[()]", "").split("[ -]");
System.out.printf("(%s) %s-%s%n", arr[0], arr[1], arr[2]);

      

which also gives your requested result

(123) 456-7890

      



+1


source


If you must use the split method:

String s= "(123) 456-7890"
String[] split = s.split("[()-]");
System.out.println("(" + split[1] + ")" + split[2] + "-" + split[3]);

      

0


source


it works:

    String s= "(123) 456-7890";
    String[] parts = s.split("[()\\- ]");
    System.out.println("(" + parts[1] + ") " + parts[3] + "-" + parts[4]);

      

0


source







All Articles