0

given the following string:

foo().bar(norf.qux).fubar()

I want to split it by the dots except when they're within parentheses, where the output would be:

foo()
bar(norf.qux)
fubar()

is this possible?

bsferreira
  • 1,189
  • 5
  • 14
  • 27
  • "*is this possible?*" [yes](http://stackoverflow.com/a/25293211/1393766), but if you can infinitely nest such expression then don't use regex here. Write your own parser. – Pshemo Oct 22 '14 at 17:36
  • One basic question: can you nest parenthesis? In other words, is something like `foo().bar(norf.qux()).fubar()` or `foo().bar(norf.qux(buz.whatever())).fubar()` possible? – Pshemo Oct 22 '14 at 17:45

2 Answers2

1

Split the input string by dot which was not enclosed within brackets.

\.(?![^()]*\))

In Java String representing this regex would be,

"\\.(?![^()]*\\))"

DEMO

String[] tok = s.split("\\.(?![^()]*\\))");
System.out.println(Arrays.toString(tok));

Output:

[foo(), bar(norf.qux), fubar()]

Pattern Explanation:

\.                       '.'
(?!                      look ahead to see if there is not:
  [^()]*                   any character except: '(', ')' (0 or
                           more times)
  \)                       ')'
)                        end of look-ahead
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You could use a simple regex like this:

\B\.

Working demo

enter image description here

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • Interesting, but I am afraid that OP is looking for regex which will split based on if `.` was not inside parenthesis, not if it was not after `)`. In that case we could simply split on `(?<=[)])\.`. – Pshemo Oct 22 '14 at 17:54
  • @Pshemo yes, I agree with you but just posted the answer because of OP sample text. This simple regex works for his example, it might be useful for him – Federico Piazza Oct 22 '14 at 17:56
  • That is OK, I am not OP so I can't definitely tell if your answer is wrong or not. I just posted my comment to add information about assumptions of your answer :) – Pshemo Oct 22 '14 at 18:00
  • Thanks, helpful too. This suites my scenario at the moment but I'm afraid that in the future I catch this one `foo().bar(norf.qux).fubar().bar(norf.qux)` and the output will be `foo().bar(norf.qux) fubar() bar(norf.qux)` not the expected, but thanks ;) – bsferreira Oct 22 '14 at 18:33
  • 1
    Hi @Lucas, thanks for the comment. Just for you to know, it also works for the example you mentioned http://regex101.com/r/kE6yQ8/2 – Federico Piazza Oct 22 '14 at 19:39
  • Yeah you're right! this was what I tried to say `foo.bar(norf.qux).fubar.bar(norf.qux)`. sorry – bsferreira Oct 23 '14 at 08:42