I am trying to cleanse some data from a file.
There is a "Name" column containing strings with names and some of them contain symbols lile "/" ,"#" ,while others contain dashes (-) or ".". Dashes and dots are allowed and should be retained.
Example:Gustav Mag$nus Oswald , Mr. Clement Fleevle Fust-Kratz
Result:
Gustav Magnus Oswald,
Mr. Clement Fleevle Fust-Kratz
So far I've come up with this: [^a-zA-Z ]+ but it it's not working.
I tried to match 3 words - ^[a-zA-Z0-9_ ]+( [a-zA-Z0-9_ ])+( [a-Za-Z0-9_ ]) *$
What I am missing ?
What about writing code like this?
String name = "Gustav M#g$nus Oswald"; // this name comes from your data source
String cleansedName = name.replace("$", "s").replace("#", "a");
So, what should happen with Strings that contain non-replacable, not allowed characters?
Try something like
String name="Gustav Mag$nus Oswald , Mr. Clement Fleevle Fust-Kratz";
String newString = name.replaceAll("[^a-zA-Zs+,-]{1,}"," ").replaceAll("\\s{1,}"," ");
System.out.println(newString);
Related
I have a string that looks like this:
analitics#gmail.com#5
And it represents my userId.
I have to send that userId as parameter to the function and send it in the way that I remove number 5 after second # and append new number.
I started with something like this:
userService.getUser(user.userId.substring(0, userAfterMigration.userId.indexOf("#") + 1) + 3
What is the best way of removing everything that comes after the second # character in string above using Java?
Here is a splitting option:
String input = "analitics#gmail.com#5";
String output = String.join("#", input.split("#")[0], input.split("#")[1]) + "#";
System.out.println(output); // analitics#gmail.com#
Assuming your input would only have two at symbols, you could use a regex replacement here:
String input = "analitics#gmail.com#5";
String output = input.replaceAll("#[^#]*$", "#");
System.out.println(output); // analitics#gmail.com#
You can capture in group 1 what you want to keep, and match what comes after it to be removed.
In the replacement use capture group 1 denoted by $1
^((?:[^#\s]+#){2}).+
^ Start of string
( Capture group 1
(?:[^#\s]+#){2} Repeat 2 times matching 1+ chars other than #, and then match the #
) Close group 1
.+ Match 1 or more characters that you want to remove
Regex demo | Java demo
String s = "analitics#gmail.com#5";
System.out.println(s.replaceAll("^((?:[^#\\s]+#){2}).+", "$1"));
Output
analitics#gmail.com#
If the string can also start with ##1 and you want to keep ## then you might also use:
^((?:[^#]*#){2}).+
Regex demo
The simplest way that would seem to work for you:
str = str.replaceAll("#[^.]*$", "");
See live demo.
This matches (and replaces with blank to delete) # and any non-dot chars to the end.
Need Regex for
Abc your request is Approved.
In above statement if word 'Approved' comes in sentence it should select whole sentence.
Mr. Abc your request is Approved.
and if word 'Mr' comes in sentence it should not select a sentence even though it contains 'Approved' word.
((?!Mr).)* matches string that doesn't contain "Mr.". If you check it before and after of the word "Approved", you're done.
^((?!Mr.).)*Approved((?!Mr.).)*$
Example:
Abc your request is Approved. -> Match
Mr. Abc your request is Approved. -> No match
Abc your request is Approved. Mr. -> No match
Abc your Mr. request is Approved. -> No match
This should do it
^(?!Mr).*(Approved).*
It will select those lines which doesn't start with Mr, but have the word Approved inside (it can or not be at the end )
Working example here
Maybe this regex can help you ^(?i)((?=\bApproved\b).)*((?!\bMr\b).)*$
String approved = "Abc your request is Approved.";
String notApproved = "Mr. Abc your request is Approved.";
String regex = "(?i)((?=\\bApproved\\b).)*((?!\\bMr\\b).)*";
If you use :
System.out.println(approved.matches(regex));
System.out.println(notApproved.matches(regex));
Outputs
true
false
Let's say I have a string with an xml many occurences of <tagA>:
String example = " (...) some xml here (...)
<tagA>283940</tagA>
(...) some xml here (...)
<tagA>& 9940</tagA>
<tagA>- 99440</tagA>
<tagA>< 99440</tagA>
<tagA>99440</tagA>
(...) more xml here (...) "
The content should contain only digits, but sometimes it has a random character followed by a whitespace and the the digits.
I want to remove the unwanted character and the whitespace. How to do that?
So far I know I should be looking for a regex "<tagA>. [0-9]*<\/tagA>" but I am stuck here.
I want to replace the characters because among those characters there are "&", ">", "<" signs which make the xml invalid (which prevents me from treating this as an XML).
The regex that you're looking for is:
<(\w+)>(\D{0,})(\d+)
On the search Group 1 you'll get the TAG, on the Group 2 you'll get your weird stuff (everything that is not a digit) and in Group 3 there's the number.
There's an "enhanced version" of this regex that might work in more situations: (\w{0,})(<\w+>)(\D{0,})(\d+)(\D{0,})(<\/\w+>)(\w{0,})
This will place in the Group 1 any whitespace that might be before the tag. Group 7 will take care of the trailing whitespaces.
Group 2 and 6 will match the opening tag and closing tag.
Group 3 and 5 will match any weird character that you might have between your value.
Group 4 will contain your value.
With the String::replaceAll, you can filter and sanitize by printing only the group 2, 4 and 6, getting rid of the rest.
//input data
String s = "<tagA>283940</tagA>\n" +
" <tagA>& 9940<</tagA>\n" +
" <tagA>- 99440</tagA>\n" +
" <tagA>< 99440</tagA>\n" +
" <tagA>99440</tagA>"
+ "<13243> asdfasdf </>";
String replaced = s.replaceAll("(\\s{0,})(<\\w+>)(\\D{0,})(\\d+)(\\D{0,})(<\\/\\w+>)(\\s{0,})", "$2$4$6");
System.out.println(replaced);
Output: <tagA>283940</tagA><tagA>9940</tagA><tagA>99440</tagA><tagA>99440</tagA><tagA>99440</tagA><13243> asdfasdf </>
I have an issue which I am facing I would really appreciate your help.
I am using java and connecting it to postgres DB. I tried writing a query with LIKE and it works, but what I am looking is regex that works similar to LIKE where white spaces are also counted.
For example lets say we have the following entries in our array from the results of the DB as
"ca ts", "cats", "ca ts"
etc. When I type
"c a ts"
in the search filter I should retrieve all the above from that array which has all the results from the database.
You may try with replacing spaces from input and search pattern:
String input = "a b c";
String searchPattern = "ab c";
Pattern pat = Pattern.compile(searchPattern.replace(" ", ""));
System.out.println(pat.matcher(input.replace(" ", "")).matches());
You don't need regex for it. EG here 'c a ts' is "like" 'ca ts':
b=# select replace('c a ts',' ','') like replace('ca ts',' ','') as example;
example
---------
t
(1 row)
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