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

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

Related

split the special charater contain inside the string

I have a String """JBL#gmail.com from which I want to remove the """ which is located at the front of the email address. I tried to use split, but unfortunately it didn't work.
Here is my code:
String [] sender1 = SA1.split(" ");
String str1 = sender1[0];
System.out.println("the str1 is :"+str1);
String [] sender2 = str1.split("\\\"");
String str2 = sender2[0];
String str3 = sender2[1];
System.out.println("the str2 is :"+str2);
System.out.println("the str3 is :"+str3);
Here is my code output-
the str1 is :"""JBL#gmail.com""
the str2 is :
the str3 is :
My SA1 will contain """JBL#gmail.com"" <JBL#gmail.com>". The email address can be a mix of lower/upper case letters, numbers, and etc.
If SA1 does in fact contain
"\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\""
then you can use Pattern/Matcher with a Regular Expression of "<(.*?)>" to retrieve the E-Mail Address from the String:
String sa1 = "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"";
String email = "";
Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher(sa1);
while (matcher.find()) {
// Is a match found?
if (!matcher.group(1).equals("")) {
// There is so place the match into the
// email variable.
email = matcher.group(1);
}
}
// Display the E-Mail Address in Console Window.
System.out.println("E-Mail Address is: " + email);
Console window will display:
E-Mail Address is: JBL#gmail.com
Regular Expression Explanation:
You can obtain the email in the first part of the string by removing all quotation marks (replace("\"", "")), spliting by spaces (split(" ")), and taking the first element in the split ([0]):
String str = "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"";
str.replace("\"", "").split(" ")[0];
Note that the second element would produce <JBL#gmail.com>.
"fdsd\"\"\" dsd".split("\"\"\"")
you have to use
"yourWords".split("\"\"\"")
String s= "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"".
split("<")[1].replace(">", "").replace("\"", "");

How to replace dollar character with backslash dollar in a string

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

I want to check if a word or a set of words exists in a String

My requirement is to check if a group of words or a single word is present in a larger string. I tried using String.contains() method but this fails in case the larger string has new line character. Currently I am using a regex mentioned below. But this works for only one word. The searched text is a user entered value and can contain more than one word. This is an android application.
String regex = ".*.{0}" + searchText + ".{0}.*";
Pattern pattern = Pattern.compile(regex);
pattern.matcher(largerString).find();
Sample String
String largerString ="John writes about this, and John writes about that," +
" and John writes about everything. ";
String searchText = "about this";
Why not just replace line breaks with spaces, and on top of that, convert it all to lower case?
String s = "hello";
String originalString = "Does this contain \n Hello?";
String formattedString = originalString.toLowerCase().replace("\n", " ");
System.out.println(formattedString.contains(s));
Edit: Thinking about it, I don't really understand how line breaks make a difference...
Edit 2: I was right. Line breaks don't matter.
String s = "hello";
String originalString = "Does this contain \nHello?";
String formattedString = originalString.toLowerCase();
System.out.println(formattedString.contains(s));
here is code not using regex.
String largerString = "John writes about this, and John writes about that," +" and John writes about everything. ";
String searchText = "about this";
Pattern pattern = Pattern.compile(searchText);
Matcher m = pattern.matcher(largerString);
if(m.find()){
System.out.println(m.group().toString());
}
Result:
about this
I hope it will help you.

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
}

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

Categories