This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to extract parameters from a given url
I'm trying to retrieve just the numbers from the parameter in this url:
htt://tesing12/testds/fdsa?communityUuid=45352-32452-52
I have tried this with no luck:
^.*communityUuid=
Any help would be nice.
I recommend against the simple string-manipulation route. It's more verbose and more error prone. You may as well get a little help from the built-in classes and then use your knowledge that you're working with a URL (parameters delimited with "&") to guide your implementation:
String queryString = new URL("http://tesing12/testds/fdsa?communityUuid=45352-32452-52").getQuery();
String[] params = queryString.split("&");
String communityUuid = null;
for (String param : params) {
if (param.startsWith("communityUuid=")) {
communityUuid = param.substring(param.indexOf('=') + 1);
}
}
if (communityUuid != null) {
// do what you gotta do
}
This gives you the benefit of checking the well-formed-ness of the URL and avoids problems that can arise from similarly named parameters (the string-manipulation route will report the value of "abc_communityUuid" as well as "communityUuid").
A useful extension of this code is to build a map as you iterate over "params" and then query the map for any parameter name you want.
I don't see any reason to use a regex.
I would just do this:
String token = "communityUuid=";
String url = "htt://tesing12/testds/fdsa?communityUuid=45352-32452-52";
int index = url.indexOf(token) + token.length();
String theNumbers = url.substring(index);
NOTE:
You might have to look for the next parameter as well:
String token = "communityUuid=";
String url = "htt://tesing12/testds/fdsa?communityUuid=45352-32452-52";
int startIndex = url.indexOf(token) + token.length();
// here's where you might want to use a regex
String theNumbers = url.substring(startIndex).replaceAll("&.*$", "");
Related
i need to read a file upto certain comma,for example;
String s=hii,lol,wow,and,finally
need output as hii,lol,wow,and
Dont want last comma followed with characters
As my code is reading last comma string
Example:iam getting my code out put as: finally
Below is my code
please guide me
File file =new File("C:/Users/xyz.txt");
FileInputStream inputStream = new FileInputStream(file);
String filke = IOUtils.toString(inputStream);
String[] pieces = filke.split("(?=,)");
String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());
String www=answer.substring(1);
System.out.format("Answer = \"%s\"%n", www);
You don't necessarily need to use regex for this. Just get the index of the last ',' and get the substring from 0 to that index:
String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and
String in Java has a method called lastIndexOf(String str). That might come in handy for you.
Say your input is String s = "hii,lol,wow,and,finally";
You can do a String operation like:
String s = "hii,lol,wow,and,finally";
s = s.substring(0, s.lastIndexOf(","));
This gives you the output: hii,lol,wow,and
If you want to use java 8 stream to do it for you maybe try filter ?
String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());
this will print Answer = "hii,lol,wow,and"
To have stricly regex you can use the Pattern.compile and Matcher
Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}
Will match hii, lol, wow, and,
See the regex example here https://regex101.com/r/1iZDjg/1
I am still a novice with regular expressions, "regex", etc... in Java.
If I have an url like this : "http://somedomain.someextention/somefolder/.../someotherfolder/somepage"
What is the simplest way to get :
"somedomain.someextention" ?
"somefolder/.../someotherfolder/somepage" ?
"somepage" ?
Thanks !
You don't have to (and probably shouldn't) use regex here. Instead use classes defined to handle things like this. You can use for example URL, URI, File classes like
String address = "http://somedomain.someextention/somefolder/.../someotherfolder/somepage";
URL url = new URL(address);
File file = new File(url.getPath());
System.out.println(url.getHost());
System.out.println(url.getPath());
System.out.println(file.getName());
Outpit:
somedomain.someextention
/somefolder/.../someotherfolder/somepage
somepage
Now you can need to get rid of / at start of path to your resource. You can use substring(1) here if resource starts with /.
But if you really must use regex you can try with
^https?://([^/]+)/(.*/([^/]+))$
Now
group 1 will contain host name,
group 2 will contain path to resource
group 3 will contain name of resource
The best way to get those components is to use the URI class; e.g.
URI uri = new URI(str);
String domain = uri.getHost();
String path = uri.getPath();
int pos = path.lastIndex("/");
...
// or use File to parse the path string.
You could do it using regexes on the raw url string, but there is a risk that you won't correctly cope with all of the variability that is possible in a URL. (Hint: the regex supplied by #Pchenko doesn't :-)) And you would definitely need to use a decoder to deal with possible percent encoding.
This is not a regexp or URI use but simple substring code as an excersise material. Missing few corner case format validation.
int lastDelim = str.lastIndexOf('/);
if (lastDelim<0) throw new IllegalArgumentException("Invalid url");
int startIdx = str.indexOf("//");
startIdx = startIdx<0 ? 0 : startIdx+2;
int pathDelim = str.indexOf('/', startIdx);
String domain = str.substring(startIdx, pathDelim);
String path = str.substring(pathDelim+1, lastDelim);
String page = str.substring(lastDelim+1);
If you would like to use regex to decode the URL instead of using the URI class, as described in the previous answers, the below link gives a nice tutorial of regex, and it explains decoding a sample URL as well. You could learn it there and try it out.
http://www.beedub.com/book/2nd/regexp.doc.html
It's not regex, or scalable at that, it works though:
public class SomeClass
{
public static void main(String[] args)
{
SomeClass sclass = new SomeClass();
String[] string =
sclass.parseURL("http://somedomain.someextention/somefolder/.../someotherfolder/somepage");
System.out.println(string[0]);
System.out.println(string[1]);
System.out.println(string[2]);
}
private String[] parseURL(String url)
{
String part1 = url.substring("http://".length(), url.indexOf("/", "http://".length()));
String part2 = url.substring("http://".length() + part1.length() + 1, url.lastIndexOf("/"));
String part3 = url = url.substring(url.lastIndexOf("/") + 1);
return new String[] { part1, part2, part3 };
}
}
Output:
somedomain.someextention
somefolder/.../someotherfolder
somepage
I have a string like
String email = "mailto://abc#gmail.com";
I want to get only the email address but without using a fixed number like
email.substring(9);
Any better approach.
The String is of the URI format so you could do
String email = "mailto://abc#gmail.com";
URI uri = URI.create(email);
String address = uri.getUserInfo() + "#" + uri.getHost();
Use a regular expression:
String email = "mailto://abc#gmail.com";
// Builds a pattern with a capturing group ()
Pattern mailtoPattern = Pattern.compile("mailto://(.*)");
// Give your string to a matcher generated by the compiled pattern
Matcher mailMatcher = mailtoPattern.matcher(email);
// If your String is correctly formatted you can attempt to capture
// the content between parenthesis
if (mailMatcher.find()) {
String mailValue = emailMatcher.group(1);
}
Using regular expressions will also help you validate the String given as input, you can even validate if the mail String is indeed a mail address (there are crazy people with all sorts of crazy expressions to validate them). I recommend you read the very thorough JavaDoc here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html.
Not using regex
String string = "mailto://abc#gmail.com";
final String PREFIX = "mailto://";
String email = string.substring(PREFIX.length());
I made an application in which I can get a field's value through a regular expression with the help of a matcher... I made a method in which I pass a field and get a response. In string today I got some odd behaviour in my response I got AgentId = 25001220052805950 and after matcher I got fake so I have to check whether a field whose name contains "AgentId" exists and verify the values.
Needed Fields:
SecondaryAgentId=fake; PrimaryAgentId=fake;
Responce :
IsPrimaryAgentId=true; AgentId=25001220052805950; MerchantID=19; Cashier=michael; IsManualPayment=1; UserID=GraceRose; Password=rose1234; AmountUserEntered=2; AmountApproved=0; AmountDifference=0; Amount=0; CustomerNameAttempts=0; ProductID=Agriculture; InvoiceID=inv7443; SiteUrl=http://www.thcelink.com/index.php/shoping/checkout/step/step-1; ReturnURL=http://220.2.3:2027/Customer/Thanks.aspx; ResponseType=1; PrimaryAgentId=fake; PrimaryCurrencyCode=fake; SecondaryAgentId=fake; SecondaryCurrencyCode=fake; MerchantName=GraceRose; EmailId=rr#myglobal.com; Query1Attempts=0; MerchantTransactionID=543; MerchantTransactionSequenceID=246; txtAmtIsVisible=false; isQuery1Executed=false; isQuery2Executed=false; Voucher=fake; Passcode=fake; Error=fake; QueryType=fake; Payer=fake; CurrencyName=fake; CurrencySymbol=fake; CustomerName=fake; EmailBody=fake; ErrorText=fake; CustomerEmailID=fake; NavigatePageValue=0; IsCustomerInsertSucess=false; IdType=fake; IdNumber=fake; AggregateAttempts=0; Voucher2=fake; PassCode2=fake; Voucher3=fake; PassCode3=fake; TransCode=0; TransactionDate=2012-06-11T12:04:52.921875+05:30; NumberInWords=fake; MerchantCompany=fake; InvoiceNumber=fake; OverPaidAmount=0; InsufficientAmount=0; OverPaymentForEmail=fake; RedirectPage=false;
Update::
private String GetString1(String strManualproResponce2, String paternField) {
// TODO Auto-generated method stub
String s = null;
if(paternField.equalsIgnoreCase("AgentId"))
{
Pattern pinPattern2 = Pattern.compile("^"+paternField + "=(.*?);");
ArrayList<String> pins2 = new ArrayList<String>();
Matcher m2 = pinPattern2.matcher(strManualproResponce2);
while (m2.find()) {
pins2.add(m2.group(1));
s = m2.group(1);
}
}else
{
Pattern pinPattern2 = Pattern.compile(paternField + "=(.*?);");
ArrayList<String> pins2 = new ArrayList<String>();
Matcher m2 = pinPattern2.matcher(strManualproResponce2);
while (m2.find()) {
pins2.add(m2.group(1));
s = m2.group(1);
}
}
return s;
}
Your question is a little bit cryptic, from what I am understanding is that the code is not working for when you would like to match/extract the value for the AgentId field. The issue seems to be with your regular expression: "^"+paternField + "=(.*?);" assumes that the text AgentId will be at the beginning of your string, which is not since at the beginning of your string you have IsPrimaryAgentId.
Also, your current regex will return true both for IsPrimaryAgentId and AgentId since they both contain the substring: AgentId. To fix this, you can either use this regex: \\s+AgentId=(.*?);, this will require a white space before the AgentId text.
Another option would be (if your AgentId will always be numerical) to use this: AgentId=(\\d+);.
I have as input a string that is a URI. how is it possible to get the last path segment (that in my case is an id)?
This is my input URL:
String uri = "http://base_path/some_segment/id"
and I have to obtain the id I have tried with this:
String strId = "http://base_path/some_segment/id";
strId = strId.replace(path);
strId = strId.replaceAll("/", "");
Integer id = new Integer(strId);
return id.intValue();
but it doesn't work, and surely there must be a better way to do it.
is that what you are looking for:
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);
alternatively
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);
import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();
Here's a short method to do it:
public static String getLastBitFromUrl(final String url){
// return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
Test Code:
public static void main(final String[] args){
System.out.println(getLastBitFromUrl(
"http://example.com/foo/bar/42?param=true"));
System.out.println(getLastBitFromUrl("http://example.com/foo"));
System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}
Output:
42
foo
bar
Explanation:
.*/ // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
// the + makes sure that at least 1 character is matched
.* // find all following characters
$1 // this variable references the saved second group from above
// I.e. the entire string is replaces with just the portion
// captured by the parentheses above
I know this is old, but the solutions here seem rather verbose. Just an easily readable one-liner if you have a URL or URI:
String filename = new File(url.getPath()).getName();
Or if you have a String:
String filename = new File(new URL(url).getPath()).getName();
If you are using Java 8 and you want the last segment in a file path you can do.
Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();
If you have a url such as http://base_path/some_segment/id you can do.
final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);
In Android
Android has a built in class for managing URIs.
Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()
If you have commons-io included in your project, you can do it without creating unecessary objects with org.apache.commons.io.FilenameUtils
String uri = "http://base_path/some_segment/id";
String fileName = FilenameUtils.getName(uri);
System.out.println(fileName);
Will give you the last part of the path, which is the id
In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path object, to take advantage of its getName(int) method.
Unfortunately, the static factory Paths.get(uri) is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.
URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();
To get the last segment in one line of code, simply nest the lines above.
Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()
To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent() method.
String secondToLast = path.getParent().getFileName().toString();
Note the getParent() method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent() would retrieve the third-to-last segment.
You can also use replaceAll:
String uri = "http://base_path/some_segment/id"
String lastSegment = uri.replaceAll(".*/", "")
System.out.println(lastSegment);
result:
id
You can use getPathSegments() function. (Android Documentation)
Consider your example URI:
String uri = "http://base_path/some_segment/id"
You can get the last segment using:
List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size() - 1);
lastSegment will be id.
I'm using the following in a utility class:
public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
throws URISyntaxException {
return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}
public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
return uri.toString().contains("/")
? (ellipsis.length == 0 ? "..." : ellipsis[0])
+ uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
: uri.toString();
}
you can get list of path segments from the Uri class
String id = Uri.tryParse("http://base_path/some_segment/id")?.pathSegments.last ?? "InValid URL";
It will return id if the url is valid, if it is invalid it returns "Invalid url"
Get URL from URI and use getFile() if you are not ready to use substring way of extracting file.