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.
source to share
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 .
source to share
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
source to share