How to replace dollar character with backslash dollar in a string - java

I have a String like this:
String str = "aLnx5$bK$#C4EFg";
And I want to replace all the dollar $ characters with backslash dollar \$, in order to get:
String expectedString = "aLnx5\$bK\$#C4EFg";

String str = "aLnx5$bK$#C4EFg";
str = str.replace("$", "\\$");

try String.replace function that replace any sequence character :
String str = "aLnx5$bK$#C4EFg";
String newStr = str.replace("$","\\$");

you can write this to replace the $ with \$
string newstring = str.replace("$", "\\$");
for more info see this java doc: string.replace

Related

String replaceAll not replacing i++;

String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
just use replace() instead of replaceAll()
String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");
or if you want replaceAll(), apply following regex
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");
Note : in the case of replace() the first argument is a character sequence, but in the case of replaceAll the first argument is regex
try this one
public class Practice {
public static void main(String...args) {
String preCode = "Helloi++;world";
String newCode = preCode.replace(String.valueOf("i++;"),"");
System.out.println(newCode);
}
}
The problem is the string that you are using to replace , that is cnsidered as regex pattern to skip the meaning you will have to use escape sequence like below.
String newCode = preCode.replaceAll("i\\+\\+;", "");

Split the string with hyphen symbol multiple occurrence using regex /java

Getting the string value using the below xpath
String noAndDate = driver.findElement(By.xpath("//*[#id='c38']/div/table/tbody/tr[1]/td/strong")).getText();
Output of the above string = 2928554 - 2009-09-18 (BOPI 2009-38)
my expected output
2928554
2009-09-18
i tried below split, but i'm not getting my expected output
String[] words = noAndDate.split("-");
Please advice/help me
You can instead try splitting on a regex alternation which looks for a hyphen surrounded by whitespace, or pure whitespace:
String input = "2928554 - 2009-09-18 (BOPI 2009-38)";
String[] parts = input.split("(\\s+-\\s+|\\s+)");
System.out.println(parts[0]);
System.out.println(parts[1]);
Demo
Try the below code-
String str = "2928554 - 2009-09-18 (BOPI 2009-38)";
String str1 = str.split(" - | ")[0];
String str2 = str.split(" - | ")[1];
This will return str1 as 2928554 and str2 as 2009-09-18.
Hope this will help you !
Just split with regex will do.
String given = "2928554 - 2009-09-18 (BOPI 2009-38)";
String [] splitted = given.split(" - |\\s+");
String result = splitted[0] +", "+splitted[1];
System.out.println(result);
prints
2928554, 2009-09-18
Use Regex capture groups, here you can see what you want in 2 groups:
(\d+)\s*-\s*(\d+\-\d+\-\d+)
() = group
Try this:
String[] words = noAndDate.split(" ");
then
System.out.println(words[0]);
System.out.println(words[2]);

How to append to beginning of java string using replace with regex?

How can I use java string replaceAll or replaceFirst to append to beginning?
String joe = "Joe";
String helloJoe = joe.replaceAll("\\^", "Hello");
Desired Output: "Hello Joe"
You don't need to escape ^ because ^ is a special meta character in regex which matches the start of a line.
String helloJoe = whatever.replaceFirst("^", "Hello ");
You could perform a simple String append with +, or String.format(String, Object...) like
String whatever = "Joe";
String helloJoe = String.format("Hello %s", whatever);
// String helloJoe = "Hello " + whatever;
System.out.println(helloJoe);
Output is (as requested)
Hello Joe

Java String tokens

I have a string line
String user_name = "id=123 user=aron name=aron app=application";
and I have a list that contains: {user,cuser,suser}
And i have to get the user part from string. So i have code like this
List<String> userName = Config.getConfig().getList(Configuration.ATT_CEF_USER_NAME);
String result = null;
for (String param: user_name .split("\\s", 0)){
for(String user: userName ){
String userParam = user.concat("=.*");
if (param.matches(userParam )) {
result = param.split("=")[1];
}
}
}
But the problem is that if the String contains spaces in the user_name, It do not work.
For ex:
String user_name = "id=123 user=aron nicols name=aron app=application";
Here user has a value aron nicols which contain spaces. How can I write a code that can get me exact user value i.e. aron nicols
If you want to split only on spaces that are right before tokens which have = righ after it such as user=... then maybe add look ahead condition like
split("\\s(?=\\S*=)")
This regex will split on
\\s space
(?=\\S*=) which has zero or more * non-space \\S characters which ends with = after it. Also look-ahead (?=...) is zero-length match which means part matched by it will not be included in in result so split will not split on it.
Demo:
String user_name = "id=123 user=aron nicols name=aron app=application";
for (String s : user_name.split("\\s(?=\\S*=)"))
System.out.println(s);
output:
id=123
user=aron nicols
name=aron
app=application
From your comment in other answer it seems that = which are escaped with \ shouldn't be treated as separator between key=value but as part of value. In that case you can just add negative-look-behind mechanism to see if before = is no \, so (?<!\\\\) right before will require = to not have \ before it.
BTW to create regex which will match \ we need to write it as \\ but in Java we also need to escape each of \ to create \ literal in String that is why we ended up with \\\\.
So you can use
split("\\s(?=\\S*(?<!\\\\)=)")
Demo:
String user_name = "user=Dist\\=Name1, xyz src=activedirectorydomain ip=10.1.77.24";
for (String s : user_name.split("\\s(?=\\S*(?<!\\\\)=)"))
System.out.println(s);
output:
user=Dist\=Name1, xyz
src=activedirectorydomain
ip=10.1.77.24
Do it like this:
First split input string using this regex:
" +(?=\\w+(?<!\\\\)=)"
This will give you 4 name=value tokens like this:
id=123
user=aron nicols
name=aron
app=application
Now you can just split on = to get your name and value parts.
Regex Demo
Regex Demo with escaped =
CODE FISH, this simple regex captures the user in Group 1: user=\\s*(.*?)\s+name=
It will capture "Aron", "Aron Nichols", "Aron Nichols The Benevolent", and so on.
It relies on the knowledge that name= always follows user=
However, if you're not sure that the token following user is name, you can use this:
user=\s*(.*?)(?=$|\s+\w+=)
Here is how to use the second expression (for the first, just change the string in Pattern.compile:
String ResultString = null;
try {
Pattern regex = Pattern.compile("user=\\s*(.*?)(?=$|\\s+\\w+=)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}

Using String's ReplaceAll with regex

How to repalace the following String combination:
word1="word2"
With the following String combination:
word1="word3"
Using word boundaries \b.
I used the following, but did't work:
String word2 = "word2";
String word3 = "word3";
String oldLine = "word1=\"" + word2 + "\"";
String newLine = "word1=\"" + word3 + "\"";
String lineToReplace = "\\b" + oldLine + "\\b";
String changedCont = cont.replaceAll(lineToReplace, newLine);
Where cont is a String that contains a lot of characters including word1="word2" String combinations.
Remove the last \b. It will not do what you think, " is not a word character.
String input = "alma word1=\"word2\"";
String replacement = "word1=\"word3\"";
String output = input.replaceAll("\\bword1=\\\"word2\\\"", replaceMent);
If you replace your lineToReplace line by this:
String lineToReplace = "\\b" + oldLine + "(?!\\w)";
It should work the way you want.
You have word boundaries \b inside your string (the ") and you are using word boundaries in your regexp . Remove that last \b for example.
The only word boundary you need is at the front - the rest of your match already has word boundaries built in (the quotes etc).
This will work:
cont.replaceAll("\\bword1=\"word2\"", "word1=\"word3\"");

Categories