tags:

views:

49

answers:

2

Hi all, I'd like a regular expression for Java that can take this string

+1 7183541169 (East coast)

And produce two groups

  • +1 7183541169
  • East coast

I'm having difficulty with escaping the round brackets.

+3  A: 

Should be:

^(.*)\((.*)\)$

This assumes no special format - it will accept digits or letters anywhere. The regex reads:

^ - Start of the string
(.*) - some letters (captured group)
\( - literal (
(.*) - more letters (captured group)
\) - literal )
$ - end of string

Keep in mind it is a relatively easy task, and you can solve it with simple string manipulation.

Kobi
+1 I was about to say you forgot to capture the first part, but then I saw that it was posted 2 secs ago and refreshed the page :)
Amarghosh
This regular expression is to greedy, it'll match many strings wich will not be correct.
Tobias P.
Thank you! One day I might get a feel for RegExes.. just not in my DNA for some reason.
Jim Blackler
@Tobias - the format can vary. As far as I know, it can be `+925-1-800-Regex (St. George's Mnt.)`
Kobi
@Jim - if that is the case, why use a regex?
Kobi
Ah ok, Jim hadn't specified the syntax, so i thought every target string will be exactly like the input.
Tobias P.
@Kobi the code is nicely compact, so it suits my needs from that perspective.
Jim Blackler
A: 
/^(\+\d{1} \d+) \(((?:\w| |-)+)\)$/i

i don't know the rules for your string, but this should work.

Tobias P.