How to get regEx for \" string in a given string - java

We need to give like this :I\"THIS IS TEST[1]\" for the data : I\"THIS IS TEST[1]\" - to be inserted into the Redshift.
But the above thing has to be done only if we have \" in the given string , So i am searching how to identify the \" in a given string, tried with regEx , but no luck. Can you please suggest here how to check if the string has \" so that if a match is found then i will replaceAll ("\"" , "\\"");
Thank you!!!

In order to check whether a String contains the string \" you must firstly match the character \ literally by adding \ to your Regular Expression and then match the " character by adding \".
The end Regular Expression is \\" and this is tested to match your provided string on https://regex101.com/
Quick test:
String regex = "\\\"";
Pattern pattern = Pattern.compile(regex);
String toTest = "hi there \". Do I match?";
boolean found = pattern.matcher(toTest).find();
System.out.println("Boolean value for whether pattern matches toTest: " + found);
Output: "Boolean value for whether pattern matches toTest: true"
After found is true, simply run your replaceAll command like so:
String#replaceAll(regex, "new value");
Note: \" is just a ". \\" will match \". \\\" will match \". Every time you want to match an additional \, just add \\ to your Regular Expression - Alternatively, if you want to match an additional " add \" to your Regular Expression

Related

Regex to replace the character after pattern match

For my Java app, i have a string that looks like:
value1: *sample", test
test: "test"
newtest: *newtest"
I need to match the character " when the string starts with *.
Tried the regex:
"(?!.*")
But this selected all the " in the input.
Was planning to replaceAll(regex, "") to remove the character.
Desired Output:
value1: *sample, test
test: "test"
newtest: *newtest
How do i get this output?
You can use
.replaceAll("(\\*\\w+)\"", "$1")
Details:
(\*\w+) - Group 1 ($1 refers to the text captured in this group)
" - a " char (just matched, not captured, so eventually removed).

Masking sensitive logs using regex

I am trying to mask the logs by chaining replace regex in logback.xml file.
%replace(%replace(%msg){'"email":(.*?),','"email":"****"'}){'"phone":(.*?),','"phone":"****"'}))
It's working, but is there any other regex solution instead of regex replace chaining?
Can we use regex something like this?
(%replace(%msg){'"(email|phone)":(:*?)','"***",'}
I tried the above but the format is not proper.
Required output is:
{"email":"****","phone":"****"}
You can use
(%replace(%msg){'"(email|phone)":[^,]*,?','"$1":"****"'})
The "(email|phone)":[^,]*,? regex matches
" - a " char
(email|phone) - Group 1 ($1): email or phone string
": - a ": string
[^,]* - zero or more chars other than a comma
,? - an optional , char.
The replacement is "$1":"****": " + Group 1 value + ":"***".
See the regex demo.

String replacement when regex reverse group is null in java

I want to convert a software version number into a github tag name by regular expression.
For example, the version of ognl is usually 3.2.1. What I want is the tag name OGNL_3_2_1
So we can use String::replaceAll(String regex, String replacement) method like this
"3.2.1".replaceAll("(\d+).(\d+).(\d+)", "OGNL_$1_$2_$3")
And we can get the tag name OGNL_3_2_1 easily.
But when it comes to 3.2, I want the regex still working so I change it into (\d+).(\d+)(?:.(\d+))?.
Execute the code again, what I get is OGNL_3_2_ rather than OGNL_3_2. The underline _ at the tail is not what I want. It is resulted by the null group for $3
So how can I write a suitable replacement to solve this case?
When the group for $3 is null, the underline _ should disappear
Thanks for your help !!!
You can make the last . + digits part optional by enclosing it with an optional non-capturing group and use a lambda as a replacement argument with Matcher.replaceAll in the latest Java versions:
String regex = "(\\d+)\\.(\\d+)(?:\\.(\\d+))?";
Pattern p = Pattern.compile(regex);
String s="3.2.1";
Matcher m = p.matcher(s);
String result = m.replaceAll(x ->
x.group(3) != null ? "OGNL_" + x.group(1) + "_" + x.group(2) + "_" + x.group(3) :
"OGNL_" + x.group(1) + "_" + x.group(2) );
System.out.println(result);
See the Java demo.
The (\d+)\.(\d+)(?:\.(\d+))? pattern (note that literal . are escaped) matches and captures into Group 1 any one or more digits, then matches a dot, then captures one or more digits into Group 2 and then optionally matches a dot and digits (captured into Group 3). If Group 3 is not null, add the _ and Group 3 value, else, omit this part when building the final replacement value.

Java regex to replace whitespaces in css class string with dots

Given a class attribute of an HTML element, I want to generate a String suitable for css selector.
For instance, the element's class attribute value:
' foo bar baz '
OR
'foo bar baz '
Should both become a css selector:
'.foo.bar.baz'
Right now, I'm using:
String classCssSelector = "." + classProp.trim().replaceAll("\\s+", ".");
But I want to get rid of the leading hardcoded "." + and the trim() and make it all one replaceAll call.
EDIT:
I used the regex provided in #anubhava's answer, but then wanted it to also match an already 'dotted' class like this:
' foo bar baz '
The following regex works for both cases:
^(?!\.)| +(?= *\S)
You can use this regex in replaceAll:
^ *| +(?= *\S)
RegEx Demo
Code:
String classCssSelector = classProp.replaceAll("^ *| +(?= *\\S)", ".");
Explanation:
^ - Match beginning
^ * - Match 0 or more spaces at start
| - Alternation in regex
| + - Match 1 more spaces after `|`
(?= *\\S) - Lookahead to make sure there is at least one non-space character after matching
space in previous match

Java String Replace Regex

I am doing some string replace in SQL on the fly.
MySQLString = " a.account=b.account ";
MySQLString = " a.accountnum=b.accountnum ";
Now if I do this
MySQLString.replaceAll("account", "account_enc");
the result will be
a.account_enc=b.account_enc
(This is good)
But look at 2nd result
a.account_enc_num=a.account_enc_num
(This is not good it should be a.accountnum_enc=b.accountnum_enc)
Please advise how can I achieve what I want with Java String Replace.
Many Thanks.
From your comment:
Is there anyway to tell in Regex only replace a.account=b.account or a.accountnum=b.accountnum. I do not want accountname to be replace with _enc
If I understand correctly you want to add _enc part only to account or accountnum. To do this you can use
MySQLString = MySQLString.replaceAll("\\baccount(num)?\\b", "$0_enc");
(num)? mean that num is optional so regex will accept account or accountnum
\\b at start mean that there can be no letters, numbers or "_" before account so it wont accept (affect) something like myaccount, or my_account.
\\b at the end will prevent other letters, numbers or "_" after account or accountnum.
It's hard to extrapolate from so few examples, but maybe what you want is:
MySQLString = MySQLString.replaceAll("account\\w*", "$0_enc");
which will append _enc to any sequence of letters, digits, and underscores that starts with account.
try
String s = " a.accountnum=b.accountnum ".replaceAll("(account[^ =]*)", "$1_enc");
it means replace any sequence characters which are not ' ' or '=' which starts the word "account" with the sequence found + "_enc".
$1 is a reference to group 1 in regex; group 1 is the expression in parenthesis (account[^ =]+), i.e. our sequence
See http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for details

Categories

Resources