2

I am trying to split the string on "." Except when a part of the string is in [ ] then I just want to return what is inside the brackets.

I have the following line of code:

"blah.blah[http://blah.blah.com/blah/blah#]".split(("(\\.|\\[(?=.*\\]))")

This returns:

 [ "blah", "blah", "http:blah", "blah", "com/blah/blah#]" ]

If instead I try:

"blah.blah[http://blah.blah.com/blah/blah#]".split(("(\\.|\\[(?:.*\\]))")

I get:

["blah", "blah"]

I'm not sure how I need to define my non capturing group so that it will split on the first [ but not capture anything after up to and including the ]

Just to clarify the array I am expecting back is

["blah", "blah", "http://blah.blah.com/blah/blah#"]

1 Answer 1

2

To do that, the best option is to use the "find" method instead of split with this pattern:

(?<=\\[)[^\\]]*(?=\\])|[^\\][.]+

Note that the order of the alternatives is important because the first win. So (?<=\\[)[^\\]]*(?=\\]) must be before [^\\][.]+

demo

Sign up to request clarification or add additional context in comments.

7 Comments

The find here would match the "." and return them. The goal is to get the strings between them.
@tiger13cubed: refresh your browser.
Thanks for your help Casmir :) Not the solution I had in mind, but it does the trick. Any way you can explain what I was doing wrong with my \[(?=.*\]) regex?
@tiger13cubed: It's simple, a lookahead doesn't consume characters, it's only a check. So all the dots between square brackets can be matched. A pattern you can use with the split method is \\.(?![^[]*])|[\\]\\[] but it is far from an efficient way.
Where can I find the "find" method?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.