How to replace single occurrence of a character in a Java string - java

I have a string where it contains different combinations of the slashes
{"result":"{\"cov_details\":[{\"issue_date\":\"UNIT
OFFICE,NEYVELI\",\"cov\":\"MCWG\"}],\"dl_number\":\"TN31Y200000784\",\"address\":\"PERIYA COLONY KO
PAVAZHANGUDI VIRUDHACHALAM TK\",\"issue_date\":\"24-03-2010\",\"dob\":\"21-03-
1981\",\"name\":\"VICNESWARAN S\",\"blood_group\":\"\",\"validity\":{\"transport\":\"\",\"non-
transport\":\"4-01-2010 to 23-03-2040\"},\"father\\\/husband\":\"SELVAM\"}","status-
code":"101","request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe"}
I want to replace all occurances of a single "" alone but ignore when "" is followed by "/" ( check out the father\\\/husband\ parameter. It should read father\/husband. How can I achieve this in Java?

Just hide "\/" by replacing it with another character sequence like "~~~", then restore it after:
String string = "father\\\\\\/husband\\";
System.out.println("Before\t:\t" + string);
System.out.println
(
"After\t:\t" + string
.replaceAll("\\\\/", "~~~")
.replaceAll("\\\\", "")
.replaceAll("~~~", "\\\\/")
);
Output:
Before : father\\\/husband\
After : father\/husband

public String replaceAll​(String regex, String replacement) accepts regex as the first parameter:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)
Fill free to specify any pattern you need:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html#sum

Related

Skip substring in String.Contains in Java

For a given string
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
How can we check if welcomeMessage contains "Welcome, you have notification" substring by escaping name variable as name variable keeps on changing?
I want to achieve
welcomeMessage.contains("Welcome, You have notification!"); //to return true
What would be the best way to skip name variable?
String#startsWith & endsWith
The String class provides specific methods:
startsWith
endsWith
Example:
boolean containsPhrases =
message.startsWith( "Welcome" )
&&
message.endsWith( ", You have notification!" )
;
very simple
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
System.out.println(welcomeMessage + " matches " + welcomeMessage.matches("Welcome.+You have notification!"));
With matches on a regular expression. There are some special regex characters that need to be escaped with a backslash, twice \\ in a regex.
welcomeMessage.matches("Welcome .*, you have notification\\!");
.* stands for . = any character without line breaks, and * = repeat the previous 0 or more times. So any string.

How to convert a string of coma separated characters to a string of strings with each string in single quotes and separated by comma

I have a string
"#72c02c, #3498db, #e67e22, #9c8061, #4765a0, #79d5b3"
I want to convert it to the following:
"'#72c02c', '#3498db', '#e67e22', '#9c8061', '#4765a0', '#79d5b3'"
Is there any way to do so?
I don't know why everyone is using regex... this needs only a simple text replace:
str = "'" + str.replace(", ", "', '") + "'";
This just puts quotes before/after commas and puts a quote at each end, which is easy to understand.
String s = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
s = s.replaceAll("(#|,)","'$1");
if (s.charAt(s.length()-1) != ',')
s = s + "'";
Might not be the most elegant solution, but it handles the case of the final item in the string not ending with a ,. Will work if it does happen to end in a comma too.
If you are able to operate with it as with the simple String object instance, the you can do it with regex ([#\w]+) and String.replaceAll() method, like:
String testString = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
System.out.println(testString.replaceAll("([#\\w]+)","'$1'"));
Where with ([#\w]+), you just take every group of alpha-numeric characters or #
Then you just replace it with '$1', where $1 is the whole group, which was found.

Validate string a+b

I would like to validate if the particular string is true or not in form of a + b
If input = a + b true
If input = a + false
if input = + b false
where a and b can be any string characters
I can think of a couple of ways:
Use a regex to match a "+" the characters before and after it.
Use String.indexOf("+") to find a "+" character and test the value of the index to see if it as the start or end of the string.
(Don't forget the cases where a or b could contain a "+" character; i.e. multiple "+" characters in the string.)
You can use regular expression (regex) to test the string. In java you can use the Pattern and Matcher classes to test if a string matches a given regex. The regex you want to use is:
String regex = ".* \\+ .*";
This regex will test for a string in the following form: "[characters] + [characters]".
Here is more information about the regex in java.

split string based on text qualifier regex java

I want to split a string based on text qualifier for example
"1","10411721","MikeTison","08/11/2009","21/11/2009","2800.00","002934538","051","New York","10411720-002",".\Images\b.jpg",".\RTF\b.rtf"
Qualifer="
Spliter = ,
I want to split string based on Spliter , but if Spliter comes inside qualifier " than ignore it and return string including Spliter .
Regular expression i am using is (?:|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)
but this regular expression only returns commas,please help me in this perspective as i am new to regular expressions
please note that if we have newline characters in string ie \r\n than it should ignore newline character
"1","10411","Muis","a","21/11/2009","2800.06","0029683778","03005136851","Awan","10411720-001",".\Images\a.jpg",".\RTF\a.rtf"
"2","08/10/2009","07:32","Call","On-Net","030092343242342376543","Monk","00:00","1.500","0.000","10.000","0.200"
"2","08/10/2009","02:50","Call","Off-Net","030092343242342376543","Une","08:00","1.500","2.000","20.000","3.500"
"2","09/10/2009","03:55","SMS","On-Net","030092343242342376543","Mink","00:00","1.500","0.000","5.000","100.500"
"2","09/10/2009","12:30","Call","Off-Net","030092343242342376543","Zog","01:01","3.500","3.000","70.000","6.500"
"2","09/10/2009","09:11","Call","On-Net","030092343242342376543","Monk","02:30","2.00","2.000","90.000","4.000"
Probably easiest solution is not searching for place to split, but finding elements which you want to return. In your case these elements
starts "
ends with "
have no " inside.
So you try with something like
String data = "\"1\",\"10411721\",\"MikeTison\",\"08/11/2009\",\"21/11/2009\",\"2800.00\",\"002934538\",\"051\",\"New York\",\"10411720-002\",\".\\Images\\b.jpg\",\".\\RTF\\b.rtf\"";
Pattern p = Pattern.compile("\"([^\"]+)\"");
Matcher m = p.matcher(data);
while(m.find()){
System.out.println(m.group(1));
}
Output:
1
10411721
MikeTison
08/11/2009
21/11/2009
2800.00
002934538
051
New York
10411720-002
.\Images\b.jpg
.\RTF\b.rtf
You can split using this regex:
String[] arr = input.split( "(?=(([^\"]*\"){2})*[^\"]*$),+" );
This regex will split on commas if those are outside double quotes by using a lookahead to make sure there are even number of quotes after a comma.
Remove the first and the last character of the whole string. Then split with ","
String test = "\"1\",\"10411721\",\"MikeTison\",\"08/11/2009\",\"21/11/2009\",\"2800.00\",\"002934538\",\"051\",\"New York\",\"10411720-002\",\".\\Images\\b.jpg\",\".\\RTF\\b.rtf\"";
if (test.length() > 0)
test = test.substring(1, test.length()-1);
System.out.println(Arrays.toString(test.split("\",\"")));
This works even if you have new line character..try it out
String str="\"1\",\"10411721\",\"MikeTison\",\"08/11/2009\",\"21/11/2009\",\"2800.00\",\"002934538\",\"051\",\"New York\",\"10411720-002\",\".\\Images\\b.jpg\",\".\\RTF\\b.rtf\"";
System.out.println(Arrays.toString(str.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)")));

Ignoring ? in a regex in String replaceFirst method

I have below program:
String one = "Hello I am IN (?)";
String two = one.replaceFirst(" IN (?)", " IN ('one','two')");
System.out.println(two);
The output is:
Hello I am IN ('one','two')(?)
The output I am expecting is:
Hello I am IN ('one','two')
What is the issue? It has to do with replaceFirst method having first argument as a regex.
replaceFirst uses a regular expression as its first argument. ( and ) are meta characters used to denote capturing groups, ? being the non-greedy quantifier
You can either escape meta characters
String two = one.replaceFirst(" IN \\(\\?\\)", " IN ('one','two')");
or (better) using the replace method as mentioned by #RJ
String two = one.replace(" IN (?)", " IN ('one','two')");
Since the first parameter of replaceFirst() is a regex, you need to escape the (?) as (?) has a special meaning in regex(read meta character).
String two = one.replaceFirst(" IN \\(\\?\\)", " IN ('one','two')");
To avoid escaping, you can use the replace() method, which doesn't take a regex as the replace string.
String two = one.replace(" IN (?)", " IN ('one','two')");
Try this one
String one = "Hello I am IN (?)";
String two = one.replaceFirst(" IN \\(\\?\\)", " IN ('one','two')");
System.out.println(two);

Categories