I have a String:
String s="<p>Dear <span>{customerName}, your {accountName} is actived </span></p><p> </p><p><span>Congrats!.....</span></p>";
So I want to take CustomerName and accountName words and replace with customers details. Can anyone please tell me how can I replace. Here customerName and accountName are dynamically changing ..because those are columns in database sometimes different columns. So i want to find the words within the { and } and need to replace with column data.
Use the following code
s = s.replace("{customerName}", realCustomerName);
s = s.replace("{accountName}", realAccountNAme);
With String's replace function, the first argument is the string you want to replace, and the second argument is the string you want to insert.
Try:
s=s.replace('{customerName}',CustomerName ).replace('{accountName}',accountName);
where CustomerName and accountName will be the strings holding your customers details
If you simply want to replace the words, you could do the following:
String s="<p>Dear <span>{customerName}, your {accountName} is actived </span></p><p> </p><p><span>Congrats!.....</span></p>";
s.replace( "{customerName}", customer.getName() );
s.replace( "{accountName}", account.getName() );
Or, if you are building the string yourself and you can modify it, it might be better to do the following:
String s="<p>Dear <span>%1$s, your %1$s is actived </span></p><p> </p><p><span>Congrats!.....</span></p>";
// You may also just create a new String object...
s = String.format( s, customer.getName(), account.getName() );
Finally, I found the answer to replace the words using regular expressions. Here words b/w ~ need to replace and these words are not fixed and dynamically will be added to string from UI text Area.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularEx {
/**
* #param args
*/
public static void main(String args[]) {
Pattern pattern = Pattern.compile("\\~.*?\\~");
StringBuilder s = new StringBuilder(
"~ABCD~~BBCc~All the best ~ABCD~~BBCc~~in~~Raja~ Such kind of people ~in~~Raja~~ABCD~~BBCc~~in~~Raja~rajasekhar~ABCD~~BBCc~~in~~Raja~ Bayanapalli ~Chinthalacheruvu~");
Matcher matcher = pattern.matcher(s);
// using Matcher find(), group(), start() and end() methods
String s1 =new String("~ABCD~~BBCc~All the best ~ABCD~~BBCc~~in~~Raja~ Such kind of people ~in~~Raja~~ABCD~~BBCc~~in~~Raja~rajasekhar~ABCD~~BBCc~~in~~Raja~ Bayanapalli ~Chinthalacheruvu~");
int i = 0;
while (matcher.find()) {
String grp = matcher.group();
int si = matcher.start();
int ei = matcher.end();
System.out.println("Found the text \"" + grp
+ "\" starting at " + si + " index and ending at index " + ei);
s1=s1.replaceAll(grp, "Raja");
//System.out.println("FinalString" + s1);
}
System.out.println("------------------------------------\nFinalString" + s1);
}
}
s = s.replace("{customerName}", "John Doe");
s = s.replace("{accountName}", "jdoe");
Related
I am trying to get a regex to match, then get the value with it. For example, I want to check for 1234 as an id and if present, get the status (which is 0 in this case). Basically its id:status. Here is what I am trying:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
Not only do I not know how to get the status without splitting and looping through, I don't know why it doesn't match the regex.
Any help would be appreciated. Thanks.
Use the Pattern class
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
The key here is to surround the position you want [0-2] in parenthesis which means it will be saved as the first group. You then access it through group(1)
I made some assumptions that your pairs we're always comma separate and then delimited by a colon. Using that I just used split.
String[] idsToCheck = topicStatus.split(",");
for(String idPair : idsToCheck)
{
String[] idPairArray = idPair.split(":");
if(idPairArray[0].equals(someId))
{
System.out.println("id : " + idPairArray[0]);
System.out.println("status: " + idPairArray[1]);
}
}
How to detect the letters in a String and switch them?
I thought about something like this...but is this possible?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
Well, if you are interested in a cheeky regex :P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
Use String.substring:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
You can use String.split e.g.
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[0];
Of course you have to also implement some error handling when there is no slash etc..
you can use string.split(separator,limit)
limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
String main ="hello/bye";
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
String[] parts = main.split("/",1);
main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
//nothing
}
Also you can use StringTokenizer to split the string.
String main = "hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
String part1 = st.nextToken();
String part2 = st.nextToken();
String newMain = part2 + "\" + part1;
I need help in splitting two email address which are seperated by a Delimiter 'AND'. I have issue when splitting, when the email address has got the characters'AND' in the email id. For eg, if the email address that needs to be split is something like the below. There are no whitespaces between the two email address.
'anandc#AND.comANDxyz#yahoo.co.in', and the delimiter is'AND'
In the above case, there seems to be three items extracted instead of two. Can someone please help me solve this. Thanks in Advance
You can use " AND " as delimiter.
String str="anandc#AND.com AND xyz#yahoo.co.in";
String[] emailArr=str.split(" AND ");
Or you can use following regex
String str = "anandc#AND.com AND xyz#yahoo.co.in";
Pattern p = Pattern.compile("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+
(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
Matcher matcher = p.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
Out put
anandc#AND.com
xyz#yahoo.co.in
Giving correct output
public class Test {
public static void main(String args[]) {
String text = "anandc#AND.com AND xyz#yahoo.co.in ";
String[] splits = text.split(" AND ");
for (int i = 0; i < splits.length; i++) {
System.out.println("data :" + splits[i]);
}
}
}
Output is
data :anandc#AND.com
data :xyz#yahoo.co.in
Use this :
String[] splits = text.split("\\s+AND\\s+");
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
the regular expression will be case sensitive
actually, the best is to use delimiters exression that you are sure will not be in the adress
I am a beginner of Java Programming language.
When I input (1,2) into the console (brackets included), how can I write the code to extract the first and the second number using RegEx?
If there is no such expression to extract the first/second number within the brackets, I will have to change the way of inputing coordinates to x,y without the brackets and that should be a lot easier to extract numbers to be used.
Try this code:
public static void main(String[] args) {
String searchString = "(7,32)";
Pattern compile1 = Pattern.compile("\\(\\d+,");
Pattern compile2 = Pattern.compile(",\\d+\\)");
Matcher matcher1 = compile1.matcher(searchString);
Matcher matcher2 = compile2.matcher(searchString);
while (matcher1.find() && matcher2.find()) {
String group1 = matcher1.group();
String group2 = matcher2.group();
System.out.println("value 1: " + group1.substring(1, group1.length() - 1 ) + " value 2: " + group2.substring(1, group2.length() - 1 ));
}
}
Not that I think regex is the best to use here. If you know the input will be in the form of: (number, number), I would first get rid of brackets:
stringWithoutBrackets = searchString.substring(1, searchString.length()-1)
and than tokenize it with split
String[] coordiantes = stringWithoutBrackets.split(",");
Looked through Regex API and you can also do something like this:
public static void main(String[] args) {
String searchString = "(7,32)";
Pattern compile1 = Pattern.compile("(?<=\\()\\d+(?=,)");
Pattern compile2 = Pattern.compile("(?<=,)\\d+(?=\\))");
Matcher matcher1 = compile1.matcher(searchString);
Matcher matcher2 = compile2.matcher(searchString);
while (matcher1.find() && matcher2.find()) {
String group1 = matcher1.group();
String group2 = matcher2.group();
System.out.println("value 1: " + group1 + " value 2: " + group2);
}
}
The main change is that I used (?<==\)), (?=,), (?<=,), (?=\)), to search for brackets and commas but not caputre them. But I really think its an overkill for this task.
I have to separate a big list of emails and names, I have to split on commas but some names have commas in them so I have to deal with that first. Luckily the names are between "quotes".
At the moment I get with my regex output like this for example (edit: it doesn't display emails in the forum I see!):
"Talboom, Esther"
"Wolde, Jos van der"
"Debbie Derksen" <deberken#casema.nl>, corine <corine5#xs4all.nl>, "
The last one went wrong cause the name had no comma so it continues until it founds one and that was the one i want to use to separate. So I want it to look until it finds '<'.
How can I do that?
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String test = "\"Talboom, Esther\" <E.Talboom#wegener.nl>, \"Wolde, Jos van der\" <J.vdWolde#wegener.nl>, \"Debbie Derksen\" <deberken#casema.nl>, corine <corine5#xs4all.nl>, \"Markies Aart\" <A.Markies#wegenernieuwsmedia.nl>";
Pattern pattern = Pattern.compile("\".*?,.*?\"");
Matcher matcher = pattern.matcher(test);
boolean found = false;
while (matcher.find ()) {
System.out.println(matcher.group());
}
edit:
better line to work with since not all have a name or quotes:
String test = "\"Talboom, Esther\" <E.Talboom#wegener.nl>, DRP - Wouter Haan <wouter#drp.eu>, \"Wolde, Jos van der\" <J.vdWolde#wegener.nl>, \"Debbie Derksen\" <deberken#casema.nl>, corine <corine5#xs4all.nl>, clankilllller#gmail.com, \"Markies Aart\" <A.Markies#wegenernieuwsmedia.nl>";
I would simplify the code by using String.split and String.replaceAll. This avoids the hassle of working with a Pattern and makes the code neat and brief.
Try this:
public static void main(String[] args) {
String test = "\"Talboom, Esther\" <E.Talboom#wegener.nl>, \"Wolde, Jos van der\" <J.vdWolde#wegener.nl>, \"Debbie Derksen\" <deberken#casema.nl>, corine <corine5#xs4all.nl>, \"Markies Aart\" <A.Markies#wegenernieuwsmedia.nl>";
// Split up into each person's details
String[] nameEmailPairs = test.split(",\\s*(?=\")");
for (String nameEmailPair : nameEmailPairs) {
// Extract exactly the parts you need from the person's details
String name = nameEmailPair.replaceAll("\"([^\"]+)\".*", "$1");
String email = nameEmailPair.replaceAll(".*<([^>]+).*", "$1");
System.out.println(name + " = " + email);
}
}
Output, showing it actually works :)
Talboom, Esther = E.Talboom#wegener.nl
Wolde, Jos van der = J.vdWolde#wegener.nl
Debbie Derksen = corine5#xs4all.nl
Markies Aart = A.Markies#wegenernieuwsmedia.nl