java - Regex for splitting a phone number -
java - Regex for splitting a phone number -
i'm trying solve problem described below:
given phone number, split country code, local area code , number. number format -
[country code]-[local area code]-[number]
country code consists of 1-3 digits, local area code consists of 1-3 digits , number 4-10 digits long (total 12 digits always).
the separator between 3 parts can either '-'(hyphen) or ' '(space).
example:
given number = 1-425-9854706 result --> grouping 1 = 1 --> country code grouping 2 = 425 --> local area code grouping 3 = 9854706 --> number
the regex i'm using same -
^(\\d{1,3})[- ](\\d{1,3})[- ](\\d{4,10})$
i take result of capture grouping 1, 2 , 3.
but regex doesn't match input test case. i'm using java.util.regex bundle if helps. please suggest improve regex same. more info problem on https://www.hackerrank.com/challenges/split-number
the code have written this:
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class solution { public static void main(string[] args) { /* come in code here. read input stdin. print output stdout. class should named solution. */ scanner sc = new scanner(system.in); int n = integer.parseint(sc.nextline()); arraylist<arraylist<integer>> output = new arraylist<arraylist<integer>>(); string s; string regex = "^(\\d{1,3})[- ](\\d{1,3})[- ](\\d{4,10})$"; pattern pattern = pattern.compile(regex); matcher matcher; for(int i=0 ; i<n ; i++) { arraylist<integer> list = new arraylist<integer>(); s = sc.nextline(); matcher = pattern.matcher(s); list.add(integer.parseint(matcher.group(1))); list.add(integer.parseint(matcher.group(2))); list.add(integer.parseint(matcher.group(3))); output.add(list); } sc.close(); for(int i=0 ; i<n ; i++) { system.out.print("countrycode="+output.get(i).get(0)+","); system.out.print("localareacode="+output.get(i).get(1)+","); system.out.print("number="+output.get(i).get(2)); system.out.println(""); } } }
it's giving me illegalstateexception, meaning "no match found".
this works:
package de.lhorn.stackoverflow; import java.util.regex.matcher; import java.util.regex.pattern; public class main { public static void main(string[] args) { pattern phonenumber = pattern .compile("^(\\d{1,3})[- ](\\d{1,3})[- ](\\d{4,10})$"); matcher matcher = phonenumber.matcher("1-425-9854706"); if (matcher.matches()) { system.out.println(matcher.group(1)); system.out.println(matcher.group(2)); system.out.println(matcher.group(3)); } } }
output:
1 425 9854706
java regex
Comments
Post a Comment