i have a java code where i select a record from db using Spring Hibernate native query and tried to strip HTML tags from a text.
String sql = " SELECT * FROM posts LIMIT 1 ";
SQLQuery query = getSession().createSQLQuery(sql);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
Map each = (Map)query.uniqueResult();
String message = (String)each.get("Message");
String content = message.replaceAll("\\<.*?\\>", "");
But why replaceAll does not work here ?
But for this code it works:
String message = "<a>blablasdddfdf</a>";
String content = message.replaceAll("\\<.*?\\>", "");
Thanks.
Both of your cases shouldn't work. In second case:
String message = "<a>blablasdddfdf</a>";
String content = content.replaceAll("\\<.*?\\>", "");
what would replaceAll method would replace in content when content hasn't been assigned any initial value?
Your last line should be:
String content = message.replaceAll("\\<.*?\\>", "");
in both of the cases to work properly.
In first case, just make sure that you have some value in message before invoking replaceAll on it.
Related
In the follwing String
String toBeFormatted= "[[LngLatAlt{longitude=-7.125924901999952, latitude=33.831783175000055, altitude=NaN},
LngLatAlt{longitude=-5.401396163999948, latitude=35.92213140900003, altitude=NaN}]]"
1- I need to replace all "LngLatAlt{longitude=" with open bracket "["
2- also need to replace all the intermediate ", latitude=33.831783175000055, altitude=NaN}" with ",33.831783175000055]"
That way my string result :
"[[[-7.125924901999952,33.831783175000055],[-5.401396163999948,35.92213140900003]]]"
try it the following reg exp :
String regexTarget = "(\\[\\[LngLatAlt\\{longitude=)";
toBeFormatted.replaceAll(regexTarget, "\\[\\[\\[");
String regexTarget0 = "(, altitude=NaN\\}, LngLatAlt\\{longitude=)";
toBeFormatted.replaceAll(regexTarget0, "],\\[");
String regexTarget1 = "(, latitude=)";
toBeFormatted.replaceAll(regexTarget1, " ,");
String regexTarget2 = "(, altitude=NaN\\})";
toBeFormatted.replaceAll(regexTarget2, "]");
but it seems not working.
Thank you for your help.
try something like:
String result = toBeFormatted.replaceAll("LngLatAlt\\{longitude=([^,]+), latitude=([^,]+), ([^}]+)\\}", "[$1, $2]");
System.out.println(result);
I have a string that saves user login name and I want to remove specific characters from that string,i want to remove "#gmail.com" and just have the name before the #, then save it as a new string?
How can I do this?
Here's an example, email can be any email address, not just gmail.com
public class Test {
public static void main(String[] args) {
String email = "nobody#gmail.com";
String nameOnly = email.substring(0,email.indexOf('#'));
System.out.println(nameOnly);
}
}
make sure the email format be correct then use "split" method to split the string from '#' character's position and use first portion of results.
var str = "username#amailserver.com";
var res = str.split("#");
var username = res[0];
You can use regex + replaceAll method of string for eliminate it
sample:
String s = "Rod_Algonquin#company.co.nz";
String newS = s.replaceAll("#(.*).(.*)", "");
System.out.println(newS);
will work on different sites extension.
if you want .org, .net , etc then you need to change the regex #(.*).(.*)
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'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 !!