Any url that starts with the pattern.. do this - java

I want to compare url A (http://www.somehost.com/citizenship) with the pattern url B (http://www.somehost.com/*) and if that URL A starts with the pattern url B then do this thing.. As URL A is originated from the URL B.. So any url that starts with this pattern.. just do this thing in the if loop... Any suggestions will be appreciated...!!
BufferedReader readbuffer = null;
try {
readbuffer = new BufferedReader(new FileReader("filters.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String strRead;
try {
while ((strRead=readbuffer.readLine())!=null){
String splitarray[] = strRead.split(",");
String firstentry = splitarray[0];
String secondentry = splitarray[1];
String thirdentry = splitarray[2];
//String fourthentry = splitarray[3];
//String fifthentry = splitarray[4];
System.out.println(firstentry + " " + secondentry+ " " +thirdentry);
URL url1 = new URL("http://www.somehost.com/citizenship");
//Any url that starts with this pattern then do whatever you want in the if loop... How can we implement this??
Pattern p = Pattern.compile("http://www.somehost.com/*");
Matcher m = p.matcher(url1.toString());
if (m.matches()) {
//Do whatever
System.out.println("Yes Done");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

What's wrong with String.startsWith(String)?
You could invoke it like this: url1.toString().startsWith("http://www.somehost.com/").
Or did I miss what you're exactly trying to achieve?
Anyways, this is the regular expression to build: http://www\.somehost\.com/.*
You need to learn regular expression syntax, in which "." mean any character so you need to escape it in between "www" and "somehost".
In Java code, you need to escape backspaces as well hence it becomes: Pattern.compile("http://www\\.somehost\\.com/.*");

I believe this should do the trick:
private final static String regexPattern = "http://www.somehost.com/[0-9a-zA-Z\\-]*/wireless-reach(/[0-9a-zA-Z\\-]*)*";
String pattern = "http://www.somehost.com/citizen-ship/wireless-reach/fil1";
if(pattern.matches(regex))
System.out.println("Matched!");

Related

Using trim() in Java to remove parts of an ouput

I have some code I wrote that outputs a batch file output to a jTextArea. Currently the batch file outputs an active directory query for the computer name, but there is a bunch of stuff that outputs as well that I want to be removed from the output from the variable String trimmedLine. Currently it's still outputting everything else and I can't figure out how to get only the computer name to appear.
Output: "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET"
I want the output to instead just show only this:
FDCD111304
Can anyone show me how to fix my code to only output the computer name and nothing else?
Look at console output (Ignore top line in console output)
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line;
BufferedWriter bw = null;
BufferedWriter writer =null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer(); // new trial
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
textArea.append(line);
textArea.append(String.format(" %s%n", line));
sbuffer.append(line + "\n");
s = sbuffer.toString();
String trimmedLine = line.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(line + System.getProperty("line.separator"));
}
fw.write("commandResult is " + s);
String input = "CN=FDCD511304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("(.*?)\\=(.*?)\\,");
Matcher m = pattern.matcher(input);
while(m.find()) {
String currentVar = m.group().substring(3, m.group().length() - 1);
System.out.println(currentVar); //store or do whatever you want
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
You could also use javax.naming.ldap.LdapName when dealing with distinguished names. It also handles escaping which is tricky with regex alone (i.e. cn=foo\,bar,dc=fl,dc=net is a perfectly valid DN)
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
Well I would personally use the split() function to first get the parts split up and then parse out again. So my (probably unprofessional and buggy code) would be
String args[] = line.split(",");
String args2[] = args[0].split("=");
String computerName = args2[1];
And that would be where this is:
while ((line = in.readLine()) != null) {
System.out.println(line);
String trimmedLine = line.trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.write(line
+ System.getProperty("line.separator"));
textArea.append(trimmedLine);
textArea.append(String.format(" %s%n", line));
}
You can use a different regular expression and Matcher.matches() to find only the value you're looking for:
String str = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("(?:.*,)?CN=([^,]+).*");
Matcher matcher = pattern.matcher(str);
if(matcher.matches()) {
System.out.println(matcher.group(1));
} else {
System.out.println("No value for CN found");
}
FDCD111304
That regular expression will find the value for CN regardless of where in the string it is. The first group is to discard anything in front of CN= (we use a group starting with ?: here to indicate that the contents of the group should not be kept), then we match CN=, then the value, which may not contain a comma and then the rest of the string (which we don't care about).
You can also use a different regex and Matcher.find() to get both the keys and values and choose which keys to act on:
String str = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("([^=]+)=([^,]+),?");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
if("CN".equals(key) || "DC".equals(key)) {
System.out.printf("%s: %s%n", key, value);
}
}
CN: FDCD111304
DC: FL
DC: NET
Try using substring to chop off the parts you dont require hence creating a new string
There're few options, simples dumbest:
str.substring(str.indexOf("=") + 1, str.indexOf(","))
Second one and more flexible approach would be to build HashArray, it would be helpful in future to read other values.
Edit: Second method
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.HashMap;
public class HelloWorld{
public static void main(String []args){
String input = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
Pattern pattern = Pattern.compile("(.*?)\\=(.*?)\\,");
Matcher m = pattern.matcher(input);
while(m.find()) {
String currentVar = m.group().substring(0, m.group().length() - 2);
System.out.println(currentVar); //store or do whatever you want
}
}
}
This one will print all values like CN=FDCD11130, you can split it by '=' and store in key/value container like HashMap or just inside list.

ReplaceAll not working on XML input

I am working on a java program that reads in XML and generates an output XML. I am having a problem replacing some of the characters in my read in file.
The following is my method:
public void readTemplateXML() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
path), "UTF8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xml = sb.toString();
xml = xml.replaceAll("<", "\\<"); //This is not working.
}
I am just outputting the "xml" string to an xml file and I am still getting "<":
<addressLine1>Main Street</addressLine1>
Is there anyway I can replace these characters with <, > ?
The encoding of the file is UTF-8.
EDIT:
the xml string is correct after the replace alls. I am using it as text content in another methods xml node:
// inner request element
Element request = doc.createElement("con:request");
request.appendChild(doc.createTextNode(xml));
rootElement.appendChild(request);
After this the content is incorrect.
Any help would be greatly appreaciated.
short answer :
Syntax:
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Parameters:
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
code :
String xml="<addressLine1>Main Street</addressLine1>&#13";
xml = xml.replaceAll("<", "\\<");
xml = xml.replaceAll(">", "\\>");
xml = xml.replaceAll("&#13", "");
System.out.println( xml );
result :
<addressLine1>Main Street</addressLine1>

Android Regular expression grab an image url from a site

I am making an app and I have this problem
I use a patter recognition code to find the image url of an article at a site.
The problem is that in my way it grabs the first photo which is extra small.
Pattern p = Pattern.compile("http://planetaris.gr/media/k2/items/cache.*\.jpg");
There is a XL image which I would like to grab its destination.
I would like to use a pattern that at the end of the link it goes like this
Pattern p = Pattern.compile("(http://planetaris.gr/media/k2/items/cache.)+(.*\[_XL]+(.jpg))");
or
Pattern p = Pattern.compile("http://planetaris.gr/media/k2/items/cache.*\_XL.jpg");
This is where I need your help
Here is the code
public void run() {
//Pattern p = Pattern.compile("http://planetaris.gr/media/k2/items/cache.*\\.jpg");
//Pattern p = Pattern.compile("http://planetaris.gr/media/k2/items/cache.*\\._XL.jpg");
Pattern p = Pattern.compile("(http://planetaris.gr/media/k2/items/cache.)+(.*\\[_XL]+(.jpg))");
try {
URL url = new URL(selectedRssItem.getLink());
URLConnection urlc = url.openConnection();
Log.d("MIMIS_LINK", url.toString());
BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
builder = new StringBuilder();
int byteRead;
while ((byteRead = buffer.read()) != -1)
builder.append((char) byteRead);
buffer.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Matcher m = p.matcher(builder.toString());
if (m.find()) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(m.group(0)).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("MIMIS_MATCHER", selectedRssItem.getDescription().toString());
};
handler.sendEmptyMessage(0);
}
}.start();
}
private Handler handler = new Handler() {
//#SuppressWarnings("null")
#Override
public void handleMessage(Message msg) {
mSpinner.clearAnimation();
mSpinner.setVisibility(View.GONE);
//progressDialog.dismiss();
myimageview.setImageBitmap(bitmap);
if (bitmap==null){
myimageview.setImageResource(R.drawable.aris_no_image);
};
}
};
because at the site there is also a jpg which has this XL
These are all the .jpg at the given page .
href="/media/k2/items/cache/df95c3d9029788dcdb6f520e9151056c_XL.jpg"
/media/k2/items/cache/df95c3d9029788dcdb6f520e9151056c_L.jpg"
"/images/stories/atnea2.jpg"
/images/stories/diarkeias-bc.jpg"
this regex: /(media|images)/[^\.]*\.jpg
matches all your samples:
href="/media/k2/items/cache/df95c3d9029788dcdb6f520e9151056c_XL.jpg"
/media/k2/items/cache/df95c3d9029788dcdb6f520e9151056c_L.jpg"
"/images/stories/atnea2.jpg"
/images/stories/diarkeias-bc.jpg"
String url = "http://planetaris.gr/media/k2/items/cache.sample_XL.jpg";
String regex = "[0-9a-zA-Z\\-\\._/:]*[XL]\\.jpg$";
System.out.println(url.matches(regex)); //this will be print true if case matches files ends with *XL.jpg and *X.jpg and *L.jpg.
You only want to check the string ends with '.jpg' use the regex
String regex = "[\\x20-\\x7E]*\\.jpg$";
If u want to find the exact match for file ends with *XL.jpg
String url = "http://planetaris.gr/media/k2/items/cache.sample_XL.jpg";
String regex = "[0-9a-zA-Z\\-\\._/:]*XL\\.jpg$";
System.out.println(url.matches(regex)); //this will be print true if case matches
If any space or special character along with 0-9a-zA-Z character coming in your URL string please use the regex.(this will return true any string that ends with *XL.jpg)
String url = "http://planetaris.gr/media/k2/items %!##$%/cache.sample_ssXL.jpg";
String regex = "[\\x20-\\x7E]*XL\\.jpg$";

SetText String[] in a TextView

I am trying to use setText, and I want to use a String array. First, I create a String [], then I assign data to String[0], then I want to .setText(String[0]) on my TextView, is this the right way?
Note : I'm using a StringTokenizer to split Strings in the textfile
try {
filename = "myk.txt";
FileReader filereader = new FileReader(Environment.getExternalStorageDirectory() + "/Q/" + filename);
BufferedReader bufferedreader = new BufferedReader(filereader);
try {
while ((text = bufferedreader.readLine()) != null){
sb.append(text);
sb.toString().split(";");
tokens = new StringTokenizer(sb.toString(), ";");
///NULLPOINTER EXEPTION HERE//// if (tokens.countTokens() > 0){questionfromfile[0] = tokens.nextToken();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
////ETC ...//// and now textview.setText(question[0]);
Sure, you mean something like
String[] strings = new String [5];
strings[0] = "foobar";
component.setText(strings[0]);
why do you have this line:
sb.toString().split(";");
?
are you forgetting that a string is immutable ,meaning that using the standard API that you use , the string will never change itself , but create new objects instead?
about StringTokenizer, as javadocs say:
StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of String
or the java.util.regex package instead.

How to use String object to parse input in Java

I'm creating a command line utility in Java as an experiment, and I need to parse a string of input from the user. The string needs to be separated into components for every occurrence of '&'. What's the best way to do this using the String object in Java.
Here is my basic code:
//Process p = null;
Process p = null;
Runtime r = Runtime.getRuntime();
String textLine = "";
BufferedReader lineOfText = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("% ");
try {
textLine = lineOfText.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//System.out.println(textLine);
}
I think the simplest way is
String[] tokens = textLine.split("&");
A Scanner or a StringTokenizer is another way to do this. But for a simple delimiter like this, the split() method mentioned by MByd will work perfectly.

Categories