Replace backslash in string - java

I have a String in which I am trying to replace the number enclosed by two backslashes. For example: \10\ , I am trying to replace that with 10. I am currently using this regex to do that:
String texter = texthb.replaceAll("\\.+\\", "\\"+String.valueOf(pertotal + initper)+"\\");
This line is giving the following error:
Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 4
.+\
I know it is because the regex is wrong. What is the proper way to accomplish this? Thanks in advance.

Use four backslashes to match a single backslash character.
String texter = texthb.replaceAll("\\\\.+?\\\\", "\\\\"+String.valueOf(pertotal + initper)+"\\\\");

Related

restricting the regular expression only for a line

I have a CSV file below from one of the system.
""demo"",""kkkk""
""demo " ","fg"
" " demo" "
"demo"
"value1","" frg" ","vaue5"
"val3",""tttyy " ",""hjhj","ghuy"
Objective is get all the 2 pair double quotes removed and only one set of double quote is allowed like below. The spaces between the sets of double quote is not a fixed value. This has to be handled in a Java program using replaceAll
function in Java
"demo","kkkk"
"demo","fg"
"demo"
"demo"
"value1","frg","vaue5"
"val3","tttyy","hjhj","ghuy"
I tired this on regex101 with "[ ]*" and it works for PHP>=7.3 version but not in Java.
Also tried [\"][\"]|[^\"]\s+[\"] but still not getting desired output. Any suggestion please for the regular expression which can be used in Java program?
Based on shown sample data, you can use:
String repl = str.replaceAll("(?:\\h*\"){2}\\h*", "\"");
RegEx Demo
RegEx Details:
(?:\h*\"){2}: Match a pair of double quotes that have 0 or more whitespaces between them
\h*: Match 0 or more whitespace
Replacement is just a "

quotes in the java regular expressions

I get a String from the JSP, containing [", e.g.
["Bulgaria
I would like to replace all the [" occurrences for [', but I don't know exactly how to do it...
I just tried:
str = str.replaceAll("[\\\"", "['");
with the result
java.util.regex.PatternSyntaxException: Unclosed character class near index 2 [\"
and
html = html.replaceAll("[\"", "['");
with the result
java.util.regex.PatternSyntaxException: Unclosed character class near index 1 [" ^
any help will be appreciated
Try this:
str.replaceAll("\\[\"", "['");
You need \\ to escape in java regex and [ is a special character in java regex, thus the \\ in front of it. " is a special character in strings so you only need one \ to escape it.
"Test[\"".replaceAll("\\[\"", "['"); // Test['

replace a single quote in a string with another single quote

I have a String with single quote. I want to replace the single quote with 2 single quotes.
I tried using
String s="Kathleen D'Souza";
s.replaceAll("'","''");
s.replaceAll("\'","\'\'");
s.replace("'","''");
s.replace("\'","\'\'");
But the single quote is not getting replaced with 2 single quotes.
reassign the replaced string to s
String s="Kathleen D'Souza";
s = s.replaceAll("'","''");
Please try
s= "test ' test";
`s.replaceAll("'","\"");` => test " test
`s.replaceAll("'","''");` => test '' test
Strings are immutable. Assign the result of replaceAll to your String:
s = s.replaceAll("'","''");
String s="Kathleen D'Souza";
s= s.replace("'", "''");
Try String#replace(). It will replace all occurrence of single ' with double ''.
Note, with the given solutions successive single quotes will be doubled, so Kathleen D''Souza turns into Kathleen D''''Souza. (I've seen users outsmart themselves like this.) If that is something you are concerned about, you can match successive single quotes with:
s = s.replaceAll("''*","''");

Any suggestion why my regex does not work?

I got the following string to extract some information from:
String: String: String Number;
Right now I'm using the following regex to get the arguments:
(.*?):(.*?):(.*?);$
This way I would get with a Matcher the following output:
group(1) = String
group(2) = String
group(3) = String Number
If I want the number I need to execute another regex on the output of the 3rd group like the following:
([a-zA-Z]* ?([0-9])?$)
Used ont the String String Number this would give me and output like
group(1) = String
group(2) = Number
I thought about combining both steps and use a regex like (.*?):(.*?):([a-zA-Z]* ?([0-9])?);$ on the String: String: String Number;-String. But this does not work and I dont see the reason.
Hwere you go, I added some extra whitespace matching, but this seems to work, you were missing the whitespace between the second : and the following string
^(.*?):\s*(.*?):\s*([a-zA-Z]*\s+([0-9])?);$

How to split this string using Java Regular Expressions

I want to split the string
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
to
name
employeeno
dob
joindate
I wrote the following java code for this but it is printing only name other matches are not printing.
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
Pattern pattern = Pattern.compile("\\[.+\\]+?,?\\s*" );
String[] split = pattern.split(fields);
for (String string : split) {
System.out.println(string);
}
What am I doing wrong here?
Thank you
This part:
\\[.+\\]
matches the first [, the .+ then gobbles up the entire string (if no line breaks are in the string) and then the \\] will match the last ].
You need to make the .+ reluctant by placing a ? after it:
Pattern pattern = Pattern.compile("\\[.+?\\]+?,?\\s*");
And shouldn't \\]+? just be \\] ?
The error is that you are matching greedily. You can change it to a non-greedy match:
Pattern.compile("\\[.+?\\],?\\s*")
^
There's an online regular expression tester at http://gskinner.com/RegExr/?2sa45 that will help you a lot when you try to understand regular expressions and how they are applied to a given input.
WOuld it be better to use Negated Character Classes to match the square brackets? \[(\w+\s)+\w+[^\]]\]
You could also see a good example how does using a negated character class work internally (without backtracking)?

Categories