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
  • 181,427
  • 30
  • 222
  • 283
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
  • 45,615
  • 5
  • 55
  • 73
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,378
  • 1
  • 18
  • 27