I´m parsing a plain text and trying to convert into an Object.
The text looks like(and i can´t change the format):
"N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
and The Object to convert:
String index;
String timestamp;
String mail;
Integer zipCode
...
I´ve tried with:
StringTokenizer st1 = new StringTokenizer(N001\";\"2014-08-12-07.11.37.352000\";\" \";\"some#email.com \";4847 ;\"street\";\"NAME SURNAME \";26 ;\"CALIFORNIA \";21);
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken(";").replaceAll("\"",""));
}
And the output is the correct one, i´ve thinking to have a counter and hardcoding with a case bucle and set the field deppending the counter, but the problem is that I have 40 fields...
Some idea?
Thanks a lot!
String line = "N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
StringTokenizer st1 = new StringTokenizer(line, ";");
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken().replaceAll("\"",""));
}
Or you can use split method and directly get a array of values using the delimiter ;
String []values = line.split(";");
then iterate through the array and get and cast the values they way you want
Regardless of the way you are parsing the file, you somehow need to define the mapping of column-to-field (and how to parse the text).
if this is a CVS file, you could use a library like super-csv. All you need to do is write a mapping definition.
I would first split your input String based on the semi-colon separator, then clean up the values.
For instance:
String input = "\"N001\";\"2014-08-12-07.11.37.352000\";\" " +
"\";\"some#email.com " +
"\";4847 ;\"street\";\"NAME " +
"SURNAME \";26 ;\"CALIFORNIA " +
"\";21 ";
// raw split
String[] split = input.split(";");
System.out.printf("Raw: %n%s%n", Arrays.toString(split));
// cleaning up whitespace and double quotes
ArrayList<String> cleanValues = new ArrayList<String>();
for (String s: split) {
String clean = s.replaceAll("[\\s\"]", "");
if (!clean.isEmpty()) {
cleanValues.add(clean);
}
}
System.out.printf("Clean: %n%s%n", cleanValues);
Output
Raw:
["N001", "2014-08-12-07.11.37.352000", " ", "some#email.com ", 4847 , "street", "NAME SURNAME ", 26 , "CALIFORNIA ", 21 ]
Clean:
[N001, 2014-08-12-07.11.37.352000, some#email.com, 4847, street, NAMESURNAME, 26, CALIFORNIA, 21]
Note
In order to map the values to your variables you will need to know their index in advance, and it will have to be consistent.
Then you can use the get(int i) method to retrieve them from your List - e.g. cleanValues.get(2) will get you the e-mail, etc.
Note (2)
If you do not know the indices in advance or they may vary, then you are in trouble.
You can of course try to get those indices by using regular expressions but I suspect you might end up complicating your life quite a bit.
you can use Java Reflection to automate your process.
Iterate over the fields
Field[] fields = dummyRow.getClass().getFields();
and set your values
SomeClass object = construct.newInstance();
field.set(object , value);
Related
I am trying to sort the values by age and I get an error. There is a method in the program where it separates the values by ",". Upon inspecting the error, it seems that it also considers the , inside the string address (which it shouldn't do). Any ideas as to how I can make it ignore the , inside the double quoted values?
Here's the part of the code where I split the values:
while ((string = input.readLine()) != null) { // Reads each line and loops until there is no more text to be read
String[] list = string.split(",", 8); // Uses "," to split the data
String name = list[0] + "," + list[1]; // The parts of data is assigned their specific variable
String email = list[2];// The parts of data is assigned their specific variable
String address = list[3];
int age = Integer.parseInt(list[4]); // Using parseInt, the data becomes an integer so comparison will be possible
String residency = list[5];
int district = Integer.parseInt(list[6]);
String gender = list[7];
person.add(new Person(name, email, address, age, residency, district, gender)); // Passes the information from the txt file
}
I know there are similar questions regarding to this. However, I tried many solutions and it just does not work for me.
I need help to extract multiple substrings from a string:
String content = "Ben Conan General Manager 90010021 benconan#gmail.com";
Note: The content in the String may not be always in this format, it may be all jumbled up.
I want to extract the phone number and email like below:
1. 90010021
2. benconan#gmail.com
In my project, I was trying to get this result and then display it into 2 different EditText.
I have tried using pattern and matcher class but it did not work.
I can provide my codes here if requested, please help me ~
--------------------EDIT---------------------
Below is my current method which only take out the email address:
private static final String EMAIL_PATTERN =
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
public String EmailValidator(String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
return email.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
return email;
}
You can separate your string into arraylist like this
String str = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
List<String> List = Arrays.asList(str.split(" "));
maybe you should do this instead of yours :
String[] Stringnames = new String[5]
Stringnames [0] = "your phonenumber"
Stringnames[1] = "your email"
System.out.println(stringnames)
Or :
String[] Stringnames = new String[2]
String[] Stringnames = {"yournumber","your phonenumber"};
System.out.println(stringnames [1]);
String.split(...) is a java method for that.
EXAMPLE:
String content = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
String[] selection = content.split(",");
System.out.println(selection[0]);
System.out.println(selection[3]);
BUT if you want to do a Regex then take a look at this:
https://stackoverflow.com/a/16053961/982161
Try this regex for phone number
[\d+]{8} ---> 8 represents number of digits in phone number
You can use
[\d+]{8,} ---> if you want the number of more than 8 digits
Use appropriate JAVA functions for matching. You can try the results here
http://regexr.com/
For email, it depends whether the format is simple or complicated. There is a good explanation here
http://www.regular-expressions.info/index.html
I'm building a Java Swing interface in which I have a HTML-styled jTextPane, which I use for displaying the current system status. I want to be able to display a few Strings (which may change over time), while using HTML to set the appearance and placement of the text. I use the line of code below to display two strings of them in the jTextPane.
jTextPane1.setText("<html><font size=\"4\" ><b><center> String A here! </center></b></font><br><br><font size=\"3\" ><center> String B here</center></font>");
What I want, is to insert two Strings (A and B) so that I can change them over time. But unfortunately, I cannot find the syntax to insert a String anywhere. Is there a simple way to do this? Thanks in advance.
Define your HTML code as template and use the placeholders %s for stringA and stringB. Then use String.format() to insert your strings. At the end set this in your TextPane.
String template = "<html><font size=\"4\" ><b><center>%s</center></b></font><br><br><font size=\"3\" ><center>%s</center></font>"
String text = String.format(template, stringA, stringB);
jTextPane1.setText(text);
jTextPane1.getDocument().insertString(offset, stringToInsert, attributes);
You can use some constant strings like:
final String PRE_HTML = "<html><font size=\"4\" ><b><center> ";
final String MID_HTML = " </center></b></font><br><br><font size=\"3\" ><center> ";
final String POST_HTML = "</center></font></html>";
And you can set like:
String strA = "String A";
String strB = "String B";
jTextPane1.setText(PRE_HTML + strA + MID_HTML + strB + POST_HTML);
You could use String.format:
jTextPane1.setText(String.format("<html><font size=\"4\" ><b><center> %s </center></b></font><br><br><font size=\"3\" ><center> %s </center></font>", a, b));
I have a lot of strings in database like this : "\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt". I want to get the file name after the last slash.
I do this just in a normal way :
str.substring(str.lastIndexOf("\\")+1)
But it doesn't work because the single slash is used for change meanings. Is there a way in java just like python to tell compiler to regard it as a plain string like this , str=r'.......' .
Or how to change the string to "\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt". So I can pass it to File Object to read this file.
how should I do this? Or other ways to solve this.
Thanks.
The column named path(varchar(150)) in the news table is like this "\LDDESKTOP\news\1362Bloomberg Document # 180691.txt"
And I do a normal select on the path.
the code :
public List<String> getNewsFileName(String startTime,String endTime) {
List<String> newsFileNames = new ArrayList<String>();
String tableName = ConfigFile.getConfig("configuration.txt","SQLServerTable");
String sql = "select Path from [" + tableName + "] where localtime >= '" + startTime + "' and localtime <= '" + endTime + "'";
try {
if(connection==null) {
InvertedIndex.logger.log(Level.SEVERE, "Database connection has not been initialized");
System.exit(-1);
}
stmt=connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String path=rs.getString(1);
newsFileNames.add(path);
}
} catch (SQLException e) {
InvertedIndex.logger.log(Level.SEVERE,"Fail to store news");
}
return newsFileNames;
}
You use Escape Sequences to specify certain special characters that also have java properties assigned to them.
In order to print a single backslash character in a string you use a set of 2 backslashes \\.
String string = new String("\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt");
String str = string.substring(string.lastIndexOf("\\")+1);
System.out.println(str);
This prints
1455Bloomberg Document # 180784.txt
Edit 1:
Once you have the string, you can pass it back using the same escape character.
String string = "\\\\LDDESKTOP\\news\\" + str;
This outputs the original
\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt
Edit 2:
Based on what you asked, in order to transform all single backslashes into double backslashes you must use both the escape sequence and the string "replace" method.
If you have this string:
String string = new String("\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt");
You need to call this code to "double" every backslash:
String newString = string.replace("\\", "\\\\");
This produces the following:
//Note this is before we print it. This illustrates all the escape sequences.
\\\\\\\\LDDESKTOP\\\\news\\\\1455Bloomberg Document # 180784.txt
The string itself will look like this:
\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt
this code :
String st = "\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt";
st = st.replace("\n", "\\n");
st = st.replace("\\", "\\\\");
String str = st.substring(st.lastIndexOf("\\")+1);
test it.
"\n" is line break.
Thanks for all the efforts you have made . Finally , I think I have found the answer.
Instead of dealing with the string in java program, I process the string using sql functions directly.
Following is what I do.
SELECT * substring(path,len(path)-charindex('\',reverse(path))+2,charindex('\',reverse(path)))
FROM News
This really does a good job !!
i need some help and guidance in displaying the splitted Strings in order.
let say, i have username, password, nonceInString. i had successfully encrypted and decrypted those. then i split the decrypted data. it was done, too.
i want to display the decrypted data in order.
something like this.
userneme: sebastian
password: harrypotter
nonce value: sdgvay1saq3qsd5vc6dger9wqktue2tz*
i tried the following code, but it didn't display like i wish to.
pls help. thanks a lot in advance.
String codeWord = username + ";" + password + ";" + nonceInString;
String encryptedData = aesEncryptDecrypt.encrypt(codeWord);
String decryptedData = aesEncryptDecrypt.decrypt(encryptedData);
String[] splits = decryptedData.split(";");
String[] variables = {"username", "password", "nonce value"};
for (String data : variables){
for (String item : splits){
System.out.println( data + ": "+ item);
}
}
Your nested for-each logic is wrong; instead, you need to explicitly pair up the elements of the array by an index:
for (int i = 0; i < variables.length; i++) {
System.out.println(variables[i] + ":" + splits[i]);
}
Note that this assumes that both arrays have the same lengths, and will throw an ArrayIndexOutBoundsException if the splits array is shorter than the variables array.
As a side note, for key-value mapping data structure, you may want to look at java.util.Map.
import java.util.*;
//...
Map<String,String> map = new HashMap<String,String>();
map.put("username", "sebastian");
map.put("password", "harrypotter");
System.out.println(map); // prints "{username=sebastian, password=harrypotter}"
System.out.println(map.get("password")); // prints "harrypotter"
thats because your inner loop will loop through all the values in splits for each element in variables.
i assume you got something like
username ..
username ..
username ..
password ..
pa....