Quickie regular expression stuck - java

I have a line of stringy goodness:
"B8&soundFile=http%3A%2F%2Fwww.example.com%2Faeero%2Fj34d1.mp3%2Chttp%3A%2F%2Fwww.example.com%2Faudfgo%2set4.mp3"
Can I use regular expressions to just extract the http up to mp3 for all times it exists?
I have tried reading the documents for regular expressions but none mention how to go FROM http to mp3. Can anyone help?

It would be better if you directly go for index based String operation.
String data = "B8&soundFile=http%3A%2F%2Fwww.example.com%2Faeero%2Fj34d1.mp3%2Chttp%3A%2F%2Fwww.example.com%2Faudfgo%2set4.mp3";
System.out.println(data.substring(data.indexOf("http"), data.indexOf(".mp3")));
Output :
http%3A%2F%2Fwww.example.com%2Faeero%2Fj34d1
B8&soundFile=http%3A%2F%2Fwww.example.com%2Faeero%2Fj34d1.mp3%2Chttp%3A%2F%2Fwww.example.com%2Faudfgo%2set4.mp3

I probably wouldn't do this with a regex. URL decode it, break it up by tokens, and parse it using Java's URL class.

Try http.+?mp3

the following should do it (assuming you want the http and mp3 as part of your match):
.*(http.*mp3)
if you just want the bits between then:
.*http(.*)mp3
for example:
String input = "B8&soundFile=http%3A%2F%2Fwww.example.com%2Faeero%2Fj34d1.mp3%2Chttp%3A%2F%2Fwww.example.com%2Faudfgo%2set4.mp3";
Pattern p = Pattern.compile(".*(http.*mp3)");
Matcher m = p.matcher(input);
if (m.find()) {
System.out.println(m.group(1));
}
gives us
http%3A%2F%2Fwww.example.com%2Faudfgo%2set4.mp3

Related

Regular Expression to find entire link in string

I have a regular expression in apex that is only grabbing part of the link I need in a string. I need it to grab the entire link.
Here is what im working with:
String myvar = 'this is an example http://test.com/testing/123654123%0A%0A%0A%';
String myvar1 = '(?:(?:(?:[a-z0-9]{3,9}:(?://)?)(?:[-;:&=+$,w]+#)?[a-z0-9.-]+|(?:www.|[-;:&=+$??,w]+#)[a-z0-9.-]+)((?:/[+~%/.w-]*)?\\??(?:[-+=&;%#.w]*)#?w*)?)';
Pattern MyPattern = Pattern.compile(myvar1);
Matcher MyMatcher = MyPattern.matcher(myvar);
while (MyMatcher.find()) {
System.debug(MyMatcher.group());
Location = MyMatcher.group();
}
This is only returning http://test.com/
I need http://test.com/testing/123654123
How can I modify the regular expression to provide the complete link?
I just need to modify my existing regex to accomplish this. How can keep as much of the regular expression im using as possible?
(?:(?:(?:[a-z0-9]{3,9}:(?://)?)(?:[-;:&=+$,w]+#)?[a-z0-9.-]+|(?:www.|[-;:&=+$??,w]+#)[a-z0-9.-]+)((?:/[+~%/.w-]*)?\\??(?:[-+=&;%#.w]*)#?w*)?)
Use this regex :
https?:\/\/[a-zA-Z0-9.\/-]*
Online demo http://regexr.com/3d7j7

find the path param using regex in the url

what is the regular expression to find the path param from the url?
http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8
Want to retrieve the value(809pA8) from the above URL using regular expression, java is preferable.
I would suggest you do something like
url.substring(url.lastIndexOf('/') + 1);
If you really prefer regexps, you could do
Matcher m = Pattern.compile("/([^/]+)$").matcher(url);
if (m.find())
value = m.group(1);
I would try:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/'), url.length()-1));
No need for regex here, I think.
EDIT: I'm sorry I made a mistake:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/')+1, url.length()));
See this code working here: https://ideone.com/E30ddC
For your simple case, regex is an overkill, as others noted. But, if you have more cases and this is why you prefer regex, give Spring's AntPathMatcher#extractUriTemplateVariables a look, if you're using Spring. It's actually better equipped for extracting path variables than regex directly. Here are some good examples.

Regex matches in Ruby, but not in Java?

Just in an attempt to get more experience with regex (while also making life easier at work) I was trying to parse some filenames in Java.
My string is this: /home/user/example/Results/ExampleFilePrefix_20140324-0500_OptionalTextThatMightContainNumbers123.csv
basically the filename will always start with ExampleFilePrefix_ followed by the timestamp, and sometimes ends with OptionalTextThatMightContainNumbers123 just depending on how the file was generated. The relevant information I want is the timestamp followed by the optional text if it exists.
I was messing around with various regular expressions and while I can get them all to work with a Ruby regex parser I can't get any of them to work in Java. I didn't keep track of them as I went, but this is my most recent attempt:
_(\w+-\w+)
Which works as expected in Ruby: http://rubular.com/r/K2BiboURRo, but doesn't even come close to matching in Java: http://fiddle.re/c7m04
I don't think it's a problem the code I've written due to the fact the online parser doesn't match, but I'll paste it here to be sure.
private String extractFileName(String filename) {
String resultNameBase = "RegexDidntMatch";
Pattern pattern = Pattern.compile("_(\\w+-\\w+)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(filename);
if (matcher.matches() && matcher.find()) {
resultNameBase = matcher.group(1);
}
return resultNameBase;
}
As always, thanks to all in advance
First of of its only matcher.find() And the catch the group 0 instead of 1.
if (matcher.find()) {
resultNameBase = matcher.group();
}
This part is problem:
if (matcher.matches() && matcher.find())
Matcher#matches() matches complete input string with your regex.
Replace that with:
if (matcher.find())

Use RegEx in Java to extract parameters in between parentheses

I'm writing a utility to extract the names of header files from JSPs. I have no problem reading the JSPs line by line and finding the lines I need. I am having a problem extracting the specific text needed using regex. After looking at many similar questions I'm hitting a brick wall.
An example of the String I'll be matching from within is:
<jsp:include page="<%=Pages.getString(\"MY_HEADER\")%>" flush="true"></jsp:include>
All I need is MY_HEADER for this example. Any time I have this tag:
<%=Pages.getString
I need what comes between this:
<%=Pages.getString(\" and this: )%>
Here is what I have currently (which is not working, I might add) :
String currentLine;
while ((currentLine = fileReader.readLine()) != null)
{
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\]*)");
Matcher matcher = pattern.matcher(currentLine);
while(matcher.find()) {
System.out.println(matcher.group(1).toString());
}}
I need to be able to use the Java RegEx API and regex to extract those header names.
Any help on this issue is greatly appreciated. Thanks!
EDIT:
Resolved this issue, thankfully. The tricky part was, after being given the right regex, it had to be taken into account that the String I was feeding to the regex was always going to have two " / " characters ( (/"MY_HEADER"/) ) that needed to be escaped in the pattern.
Here is what worked (thanks to the help ;-)):
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\\"]*)");
This should do the trick:
<%=Pages\\.getString\\(\\\\\"([^\\\\]*)
Yeah that's a scary number of back slashes. matcher.group(1) should return MY_HEADER. It starts at the \" and matches everything until the next \ (which I assume here will be at \")%>.)
Of course, if your target text contains a backslash (\), this will not work. But you didn't give an indication that you'd ever be looking for something like <%=Pages.getString(\"Fun!\Yay!\")%> -- where this regex would only return Fun! and ignore the rest.
EDIT
The reason your test case was failing is because you were using this test string:
String currentLine = "<%=Pages.getString(\"MY_HEADER\")%>";
This is the equivalent of reading it in from a file and seeing:
<%=Pages.getString("MY_HEADER")%>
Note the lack of any \. You need to use this instead:
String sCurrentLine = "<%=Pages.getString(\\\"MY_HEADER\\\")%>";
Which is the equivalent of what you want.
This is test code that works:
String currentLine = "<%=Pages.getString(\\\"MY_HEADER\\\")%>";
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\]*)");
Matcher matcher = pattern.matcher(currentLine);
while(matcher.find()) {
System.out.println(matcher.group(1).toString());
}

Extracting URLs from a text document using Java + Regular Expressions

I'm trying to create a regular expression to extract URLs from text documents using Java, but thus far I've been unsuccessful. The two cases I'm looking to capture are listed below:
URLs that start with http://
URLs that start with www. (Missing the protocol from the front)
along with the query string parameters.
Thanks! I wish I really knew Regular expressions better.
Cheers,
If you want to make sure you are really matching a url adress and not only some word starting with 'www.' you can use the expression mentioned by DVK before. I modified it slightly and wrote a small code snippet to be a starting point for you:
import java.util.*;
import java.util.regex.*;
class FindUrls
{
public static List<String> extractUrls(String input) {
List<String> result = new ArrayList<String>();
Pattern pattern = Pattern.compile(
"\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" +
"(\\w+:\\w+#)?(([-\\w]+\\.)+(com|org|net|gov" +
"|mil|biz|info|mobi|name|aero|jobs|museum" +
"|travel|[a-z]{2}))(:[\\d]{1,5})?" +
"(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" +
"((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" +
"(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" +
"(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
result.add(matcher.group());
}
return result;
}
}
All RegEx -based code is over-engineered, especially code from the most voted answer, and here is why: it will find only valid URLs! As a sample, it will ignore anything starting with "http://" and having non-ASCII characters inside.
Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...
Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with "http://" etc., and to concatenate tokens into text again.
If you really want to use RegEx with Java, try Automaton
This link has very good URL RegExs (they are surprisingly hard to get right, by the way - thinh http/https; port #s, valid characters, GET strings, pound signs for anchor links, etc...)
http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/
Perl has CPAN libraries that contain cannedRegExes, including for URLs. Not sure about Java though :(
This tests a certain line if it is a URL
Pattern p = Pattern.compile("http://.*|www\\..*");
Matcher m = p.matcher("http://..."); // put here the line you want to check
if(m.matches()){
so something
}

Categories