Java String spit using regex with single forward slash not followed by a slash

Clash Royale CLAN TAG#URR8PPP
Java String spit using regex with single forward slash not followed by a slash
I want to split the URL by a forward slash, not by two forward slash.
http://www.eclipse.org/swt/snippets/
I want to split above URL as http://www.eclipse.org, swt, snippets.
Code:
url = http://www.eclipse.org/swt/snippets/;
String truncUrl = url.split("/");
Please guide me with regex.
Thanks,
You forgot to add your code
– manfromnowhere
Jun 25 at 4:39
Thanks. I do not want host, I just want to truncate URL for second path.
– ashkus
Jun 25 at 4:40
try showing us with code what you want to do
– Scary Wombat
Jun 25 at 4:40
2 Answers
2
You want a combination of a negative lookbehind (that is, "not preceded by") and a negative lookahead (that is, "not followed by"). So you'll split on any / that's not preceded by a / and not followed by a /.
/
/
/
According to the Javadoc for Pattern -
(?<!
)
(?!
)
So the regular expression you want is (?<!/)/(?!/)
(?<!/)/(?!/)
As an additional answer,
you may use this expression ((?:http(s)?://)?[w.&?=%#+:-]+)
((?:http(s)?://)?[w.&?=%#+:-]+)
Example:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.ArrayList;
public class MyClass
public static void main(String args)
String url = "https://stackoverflow.com/questions/51016377/java-string-spit-using-regex-with-single-forward-slash-not-followed-by-a-slash";
Pattern rgx = Pattern.compile("((?:http(s)?://)?[\w.&?=%#+:-]+)");
Matcher m = rgx.matcher(url);
List<String> list = new ArrayList<>();
while (m.find())
list.add(m.group(1));
list.forEach(System.out::println);
Output:
https://stackoverflow.com
questions
51016377
java-string-spit-using-regex-with-single-forward-slash-not-followed-by-a-slash
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you probably don't need a regex for that. Any url parser can tell you what the protocol is, and what the host is. (see docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html)
– njzk2
Jun 25 at 4:39