1

I have a string that looks like:

Hi, <name> pls visit <url>

Now i would like to split the string into an array with a regex.

I have tried this:

hi.split("(?=<[A-Za-z]+>)");
Output: [Hi, , <name> pls visit , <url>]

But i would like to have

[Hi, , <name> , pls visit , <url>]

Is there a chance to do that ?

Nosxxx
  • 31
  • 4

3 Answers3

4
String s="Hi, <name> pls visit <url>";
String[] ss = s.split("(?<=> )|(?=<)");
System.out.println(Arrays.toString(ss));

the above codes output:

[Hi, , <name> , pls visit , <url>]
Kent
  • 189,393
  • 32
  • 233
  • 301
3

You can try

String str="Hi, <name> pls visit <url>";
System.out.println(Arrays.toString(str.split("(?=<)|(?<=> )")));

output:

[Hi, , <name> , pls visit , <url>]

Here is online demo


(?=<)|(?<=> )

Regular expression visualization

Debuggex Demo


Pattern explanation:

  (?=                      look ahead to see if there is:
    <                        '<'
  )                        end of look-ahead
 |                        OR
  (?<=                     look behind to see if there is:
    >                        '> '
  )                        end of look-behind
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 1
    he wanted `(space)` – Kent Aug 21 '14 at 13:44
  • how did you get the shared link from reg101? must be registered user or what? I cannot find that feature. – Kent Aug 21 '14 at 13:50
  • @Kent regex101 is free for everyone. Just click on `save regex` link. Are you not getting it? – Braj Aug 21 '14 at 13:52
  • Thanks, I didn't think that "save regex" will do that. :-), I kept looking for "share regex" or "perm link" sth. like that. – Kent Aug 21 '14 at 13:53
0

You're already using lookahead, I believe the Java-flavor of regex has lookbehind as well. So something like:

hi.split("(?=<[A-Za-z_]\\w*>)|(?<=<[A-Za-z_]\\w*>)");

(note: I changed it to [A-Za-z_]\w* so <_this3> would also match but <5thing> would not)

asontu
  • 4,548
  • 1
  • 21
  • 29