1

I need to split my text into pieces and also keep the delimiter as well, I know I can use below code to do that as explained Here:

Arrays.toString("a;b;c;d".split("((?<=;)|(?=;))"))

but what I'm stuck is that my text contains delimiter with a value inside it, my delimiter is @[x]@ where x is a value which can be any number. eg: @[1]@, @[44]@. What I want to achieve is to get an array as below:

text : "Hello my Name is blabla.@[1]@How are you today?@[2]@ByeBye"

and what I need to get:

[ "Hello my Name is blabla.", "@[1]@", "How are you today?", "@[2]@", "ByeBye" ]

How can I achieve that? Thanks in advance.

Community
  • 1
  • 1
arash moeen
  • 4,533
  • 9
  • 40
  • 85

1 Answers1

2

Try the following regex as a delimiter:

((?<=(@\\[\\d\\]@))|(?=(@\\[\\d\\]@)))

basically replacing the semi-colon with the expression (@\\[\\d\\]@) where \d matches any digit.

If more than one digit can exist, you can specify a range for the possible number of digits, for example \d{1,1000} instead of \d to have a maximum of 1000 digits. An unknown number of digits using an expression like \d+ cannot be used with Java lookbehind regular expressions.

M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    @Pshemo Thanks for correcting me! I completely missed that. – M A Feb 24 '15 at 18:05
  • Sorry for bumping this up again but \d+ worked perfectly fine in my case, for example "blablabla.@[1]@blablabla@[27]@ worked like a charm. – arash moeen Mar 18 '15 at 10:56