#Path("/{code:.+}")
public Response getTemplateForCode(#PathParam("code") String code)
I want to pass URI in path parameter eg(ABC://HELLO). But iam getting only single slash ABC:/HELLO only. Can anyone tell how to get double slashes with full uri ABC://HELLO. Is there any REGEX to get double slashes?
I don't want to pass in query params
In Java regex we can use a backslash to escape the special meaning of a slash.
The pattern
\w+:\/\/\w+
matches
ABC://HELLO
See https://regex101.com/r/5vRHHN/1
Related
Context: GoogleBooks API returing unexpected thumbnail url
Ok so i found the reason for the problem i had in that question
what i found was the returned url from the googlebooks api was something like this:
http:/\/books.google.com\/books\/content?id=0DwKEBD5ZBUC&printsec=frontcover&img=1&zoom=5&source=gbs_api
Going to that url would return a error, but if i replaced the "\ /"s with "/" it would return the proper url
is there something like a java/kotlin regex that would change this http:/\/books.google.com\/ to this http://books.google.com/
(i know a bit of regex in python but I'm clueless in java/kotlin)
thank you
You can use triple-quoted string literals (that act as raw string literals where backslashes are treated as literal chars and not part of string escape sequences) + kotlin.text.replace:
val text = """http:/\/books.google.com\/books\/content?id=0DwKEBD5ZBUC&printsec=frontcover&img=1&zoom=5&source=gbs_api"""
print(text.replace("""\/""", "/"))
Output:
http://books.google.com/books/content?id=0DwKEBD5ZBUC&printsec=frontcover&img=1&zoom=5&source=gbs_api
See the Kotlin demo.
NOTE: you will need to double the backslashes in the regular string literal:
print(text.replace("\\/", "/"))
If you need to use this "backslash + slash" pattern in a regex you will need 2 backslashes in the triple-quoted string literal and 4 backslashes in a regular string literal:
print(text.replace("""\\/""".toRegex(), "/"))
print(text.replace("\\\\/".toRegex(), "/"))
NOTE: There is no need to escape / forward slash in a Kotlin regex declaration as it is not a special regex metacharacter and Kotlin regexps are defined with string literals, not regex literals, and thus do not need regex delimiters (/ is often used as a regex delimiter char in environments that support this notation).
You could match the protocol, and then replace the backslash followed by a forward slash by a forward slash only
https?:\\?/\\?/\S+
Pattern in Java
String regex = "https?:\\\\?/\\\\?/\\S+";
Java demo | regex demo
For example in Java:
String regex = "https?:\\\\?/\\\\?/\\S+";
String string = "http:/\\/books.google.com\\/books\\/content?id=0DwKEBD5ZBUC&printsec=frontcover&img=1&zoom=5&source=gbs_api";
if(string.matches(regex)) {
System.out.println(string.replace("\\/", "/"));
}
}
Output
http://books.google.com/books/content?id=0DwKEBD5ZBUC&printsec=frontcover&img=1&zoom=5&source=gbs_api
I had same problem and my url was:
String url="https:\\/\\/www.dailymotion.com\\/cdn\\/H264-320x240\\/video\\/x83iqpl.mp4?sec=zaJEh8Q2ahOorzbKJTOI7b5FX3QT8OXSbnjpCAnNyUWNHl1kqXq0D9F8iLMFJ0ocg120B-dMbEE5kDQJN4hYIA";
I solved it with this code:
replace("\\/", "/");
I have a part of HTML from a website in the below String format:
srcset=" /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#200w.jpg?20170808 200w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#338w.jpg?20170808 338w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#445w.jpg?20170808 445w, tesla_theme/assets/img/homepage/mobile/homepage-models--touch#542w.jpg?20170808 542w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w"
I want to add http://tesla.com in front of all the urls in the srcset element like http://tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w
I believe this could be done using regex, but I am not sure.
How do I do this using Java if I have multiple srcset elements in a html string variable, and I want to replace all of the srcset url.'s and add the server url in front?
Note: The /tesla_theme will not be consistent, so I cannot use replaceAll, instead, i will have to use regex.
You can simply use String Class replace method as below, It will replace all "/_tesla" in the given String. No special regex required unless you have a kind of pattern instead of "/tesla"
String srcset=" /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#200w.jpg?20170808 200w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#338w.jpg?20170808 338w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#445w.jpg?20170808 445w, tesla_theme/assets/img/homepage/mobile/homepage-models--touch#542w.jpg?20170808 542w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w";
String requiredSrcSet = srcset.replace("/tesla_", "http://tesla_");
I am trying to match strings v1 and v2. For that, I am trying the following regex : ^v(1|2) (I also tried with $ which is probably what I need). When I test it in http://www.regextester.com/, it seems to work fine. But when I used it in JAX-RS path expression it doesn't work. The expression I use is below:
#Path("/blah/{ver:^v(1|2)}/ep")
Is there anything specific to JAX-RS that I am missing?
Your attempt does not work because of the anchor ^. Quoting from the JAX-RS specification, chapter 3.7.3 (emphasis mine):
The function R(A) converts a URI path template annotation A into a regular expression as follows:
URI encode the template, ignoring URI template variable specifications.
Escape any regular expression characters in the URI template, again ignoring URI template variable specifications.
Replace each URI template variable with a capturing group containing the specified regular expression or ‘([ˆ/]+?)’ if no regular expression is specified.
If the resulting string ends with ‘/’ then remove the final character.
Append ‘(/.*)?’ to the result.
Because each URI templates is placed inside a capturing group, you can't embed anchors in it.
As such, the following will work and will match v1 or v2:
#Path("/blah/{ver:v[12]}/ep")
Try the following (without anchors):
#Path("/blah/{ver : v(1|2)}/ep")
Also, if the change is a single character only, use character set instead of the | operator:
#Path("/blah/{ver : v[12]}/ep")
For the given url like "http://google.com//view/All/builds", i want to replace the double slash with single slash. For example the above url should display as "http://google.com/view/All/builds"
I dint know regular expressions. Can any one help me, how can i achieve this using regular expressions.
To avoid replacing the first // in http:// use the following regex :
String to = from.replaceAll("(?<!http:)//", "/");
PS: if you want to handle https use (?<!(http:|https:))// instead.
Is Regex the right approach?
In case you wanted this solution as part of an exercise to improve your regex skills, then fine. But what is it that you're really trying to achieve? You're probably trying to normalize a URL. Replacing // with / is one aspect of normalizing a URL. But what about other aspects, like removing redundant ./ and collapsing ../ with their parent directories? What about different protocols? What about ///? What about the // at the start? What about /// at the start in case of file:///?
If you want to write a generic, reusable piece of code, using a regular expression is probably not the best appraoch. And it's reinventing the wheel. Instead, consider java.net.URI.normalize().
java.net.URI.normalize()
java.lang.String
String inputUrl = "http://localhost:1234//foo//bar//buzz";
String normalizedUrl = new URI(inputUrl).normalize().toString();
java.net.URL
URL inputUrl = new URL("http://localhost:1234//foo//bar//buzz");
URL normalizedUrl = inputUrl.toURI().normalize().toURL();
java.net.URI
URI inputUri = new URI("http://localhost:1234//foo//bar//buzz");
URI normalizedUri = inputUri.normalize();
Regex
In case you do want to use a regular expression, think of all possibilities. What if, in future, this should also process other protocols, like https, file, ftp, fish, and so on? So, think again, and probably use URI.normalize(). But if you insist on a regular expression, maybe use this one:
String noramlizedUri = uri.replaceAll("(?<!\\w+:/?)//+", "/");
Compared to other solutions, this works with all URLs that look similar to HTTP URLs just with different protocols instead of http, like https, file, ftp and so on, and it will keep the triple-slash /// in case of file:///. But, unlike java.net.URI.normalize(), this does not remove redundant ./, it does not collapse ../ with their parent directories, it does not other aspects of URL normalization that you and I might have forgotten about, and it will not be updated automatically with newer RFCs about URLs, URIs, and such.
String to = from.replaceAll("(?<!(http:|https:))[//]+", "/");
will match two or more slashes.
Here is the regexp:
/(?<=[^:\s])(\/+\/)/g
It finds multiple slashes in url preserving ones after protocol regardless of it.
Handles also protocol relative urls which start from //.
#Test
public void shouldReplaceMultipleSlashes() {
assertEquals("http://google.com/?q=hi", replaceMultipleSlashes("http://google.com///?q=hi"));
assertEquals("https://google.com/?q=hi", replaceMultipleSlashes("https:////google.com//?q=hi"));
assertEquals("//somecdn.com/foo/", replaceMultipleSlashes("//somecdn.com/foo///"));
}
private static String replaceMultipleSlashes(String url) {
return url.replaceAll("(?<=[^:\\s])(\\/+\\/)", "/");
}
Literally means:
(\/+\/) - find group: /+ one or more slashes followed by / slash
(?<=[^:\s]) - which follows the group (*posiive lookbehind) of this (*negated set) [^:\s] that excludes : colon and \s whitespace
g - global search flag
I suggest you simply use String.replace which documentation is http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence)
Something like
`myString.replace("//", "/");
If you want to remove the first occurence:
String[] parts = str.split("//", 2);
str = parts[0] + "//" + parts[1].replaceAll("//", "/");
Which is the simplest way (without regular expression). I don't know the regular expression corresponding, if there is an expert looking at the thread.... ;)
I want to use this API REST method
http://datos.santander.es/api/rest/datasets/control_flotas_estimaciones.json?query=ayto\:paradaId:454&data=ayto:paradaId,ayto:etiqLinea,ayto:tiempo1,ayto:destino1
If you see the URL, there is a param "ayto\:paradaId:454" that uses a backslash
When i try to use it in Android, I get a IllegalFormatException because of the backslash
HttpGet get = new
HttpGet("http://datos.santander.es/api/rest/datasets/control_flotas_estimaciones.json?query=ayto\:paradaId:454&data=ayto:paradaId,ayto:etiqLinea,ayto:tiempo1,ayto:destino1");
Is there any way that i can use this URL? Alternatives?
Thanks a lot!
EDIT:
I also tried to put "ayto\\:paradaId" with two backslash and i got the same exception when I get the URI...
You have to escape the backslash:
"...query=ayto\\:paradaId..."
^^
To prove that this is only one character, you can check
"\\".length()