How to replace string values with "XXXXX" in java? - java

I want to replace particular string values with "XXXX". The issue is the pattern is very dynamic and it won't have a fixed pattern in input data.
My input data
https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme
I need to replace the values of userId and password with "XXXX".
My output should be -
https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXX&password=XXXX&reme
This is an one off example. There are other cases where only userId and password is present -
userId=12345678&password=stackoverflow&rememberID=
I am using Regex in java to achieve the above, but have not been successful yet. Appreciate any guidance.
[&]([^\\/?&;]{0,})(userId=|password=)=[^&;]+|((?<=\\/)|(?<=\\?)|(?<=;))([^\\/?&;]{0,})(userId=|password=)=[^&]+|(?<=\\?)(userId=|password=)=[^&]+|(userId=|password=)=[^&]+
PS : I am not an expert in Regex. Also, please do let me know if there are any other alternatives to achieve this apart from Regex.

This may cover given both cases.
String maskUserNameAndPassword(String input) {
return input.replaceAll("(userId|password)=[^&]+", "$1=XXXXX");
}
String inputUrl1 =
"https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String inputUrl2 =
"userId=12345678&password=stackoverflow&rememberID=";
String input = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String maskedUrl1 = maskUserNameAndPassword(inputUrl1);
System.out.println("Mask url1: " + maskUserNameAndPassword(inputUrl1));
String maskedUrl2 = maskUserNameAndPassword(inputUrl1);
System.out.println("Mask url2: " + maskUserNameAndPassword(inputUrl2));
Above will result:
Mask url1: https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXXX&password=XXXXX&reme
Mask url2: userId=XXXXX&password=XXXXX&rememberID=

String url = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String masked = url.replaceAll("(userId|password)=[^&]+", "$1=XXXX");
See online demo and regex explanation.
Please note, that sending sensitive data via the query string is a big security issue.

I would rather use a URL parser than regex. The below example uses the standard URL class available in java but third party libraries can do it much better.
Function<Map.Entry<String, String>, Map.Entry<String, String>> maskUserPasswordEntries = e ->
(e.getKey().equals("userId") || e.getKey().equals("password")) ? Map.entry(e.getKey(), "XXXX") : e;
Function<List<String>, Map.Entry<String, String>> transformParamsToMap = p ->
Map.entry(p.get(0), p.size() == 1 ? "" : p.get(p.size() - 1));
URL url = new URL("https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme");
String maskedQuery = Stream.of(url.getQuery().split("&"))
.map(s -> List.of(s.split("=")))
.map(transformParamsToMap)
.map(maskUserPasswordEntries).map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&"));
System.out.println(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + "?" + maskedQuery);
Output:
https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXX&password=XXXX&reme=

Just use the methods replace/replaceAll from the String class, they support Charset aswell as regex.
String url = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
url = url.replaceAll("(userId=.+?&)", "userId=XXXX&");
url = url.replaceAll("(password=.+?&)", "password=XXXX&");
System.out.println(url);
I'm not a regex expert either, but if you find it useful, I usually use this website to test my expressions and as a online Cheatsheet:
https://regexr.com

Use:
(?<=(\?|&))(userId|password)=(.*?)(?=(&|$))
(?<=(\?|&)) makes sure it’s preceded by ? or & (but not part of the match)
(userId|password)= matches either userId or password, then =
(.*?) matches any char as long as the next instruction cannot be executed
(?=(&|$)) makes sure the next char is either & or end of the string, (but not part of the match)
Then, replace with $2=xxxxx (to keep userId or password) and choose replaceAll.

Related

Get specific words from a string in Java

If I have the following URL:
http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0
How can I get the name of the plugin (simply named wordpressplugin in the URL) and the version so the output will be - wordpressplugin ver 1.0?
I am posting my comment as an answer
String s = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
String[] ary = s.split("/");
System.out.println(ary[5] + " " + ary[7]);
Easiest way this is acc to your question,
you have to use regex for more dynamic searching.
You may do it like so, using Regex support in Java.
String url = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
Pattern pattern = Pattern.compile("(.*plugins/)(.*)(/\\d{3}/)(ver.*)");
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
System.out.println("Plugin: " + matcher.group(2));
System.out.println("Version: " + matcher.group(4));
}
Notice the use of capture groups. Here's the output.
Plugin: wordpressplugin
Version: ver=1.0
You should have a look into Regular Expressions (in Oracle tutorials), which are the general tool in any programming language to get/match sub-strings out of a larger string (which follows some more or less fixed format).
Because you claim to be new to JAVA, here is a very simple answer that should suit your skills
String url = "http://www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0";
String search = "plugins/";
int index = url.indexOf(search);
String pluginName, version;
if (index > -1)
{
index += search.length;
pluginName = url.substring(index, url.indexOf("/",index + 1));
search = "ver=";
index = url.indexOf(search);
if (index > -1)
{
version = url.substring(index + search.length);
System.out.prinln(pluginName + " " + version);
}
}
PS: This would work if and only if your url format always remains the same!
The fastest way to solve this problem is to take advantage of the split method of Strings. Just study the method below carefully, it's basic.
public String getVersionNumber(String url){
String[] arr0 = url.split("//");
//The code above returns an array of two strings: "http:" and "www.example.com/wordpress/plugins/wordpressplugin/123/ver=1.0"
String[] arr1 = arr0[1].split("/");
//The code above returns an array of six strings: "www.example.com", "wordpress", "plugins", "wordpressplugin", "123" and "ver=1.0".
return String.format("%s %s", arr1[3], arr1[5]);
//OUTPUT: wordpressplugin ver=1.0
//I simply returned what I needed.
}
I hope this helps.. merry coding!

Accept everything in java if condition

today I wrote a programm that automaticaly checks if an Netflix account is working or not. But I'm struggling at a point where I need to accept all the country codes in the URL. I wanted to use something like * in linux but my IDE is giving me Errors. What is the Solution and are there better ways?
WebUI.openBrowser('')
WebUI.navigateToUrl('https://www.netflix.com/login')
WebUI.setText(findTestObject('/Page_Netflix/input_email'), 'example#gmail.com')
WebUI.setText(findTestObject('/Page_Netflix/input_password'), '1234')
WebUI.click(findTestObject('/Page_Netflix/button_Sign In'))
TimeUnit.SECONDS.sleep(10)
if (WebUI.getUrl() == "https://www.netflix.com/" + * + "-" + * + "/login") {
}
WebUI.closeBrowser()
So this is your attempt:
if (WebUI.getUrl() == "https://www.netflix.com/" + * + "-" + * + "/login") {
}
which fails, as you can't just use * like that (in addition to using ==, which isn't what you should do when using java). But I think this is what you want:
if (WebUI.getUrl().matches("https://www\\.netflix\\.com/.+-.+/login")) {
// do whatever
}
which would match in whatever country you are in: any url like https://www.netflix.com/it-en/login. If within the if statement you need to use the country information, you'll might want a matcher:
import java.util.regex.*;
Pattern p = Pattern.compile("https://www\\.netflix\\.com/(.+)-(.+)/login");
Matcher m = p.matcher(WebUI.getUrl());
if (m.matches()) {
String country = m.group(1);
String language = m.group(2);
// do whatever
}
Note that we're using java here, as you have the question tagged like that. Katalon is able to use also javascript and groovy, which you've also used in your single-quote strings and leaving out semicolons. In groovy, == for string comparison is ok, and it can also use shorthands for regular expressions.
You could create a list of pair valid values for the country codes if you want to keep track of which country you are in, and the just compare the two strings.
If you don't want to do it that way and accept everything it comes in the url string, then I recommend you using split method:
String sections[] = (WebUI.getUrl()).split("/");
/* Now we have:
sections[0] = "https:""
sections[1] = ""
sections[2] = "www.netflix.com"
sections[3] = whatever the code country is
sections[4] = login
*/
Try to solve it with regular expression on URL string:
final String COUNTRY_CODES_REGEX =
"Country1|Country2|Country3";
Pattern pattern = Pattern.compile(COUNTRY_CODES_REGEX);
Matcher matcher = pattern.matcher(WebUI.getUrl());
if (matcher.find()) {
// Do some stuff.
}
Instead of using WebUI.getUrl() == ...
you could use String.matches (String pattern). Similarly to AutomatedOwl's reply you would define a String variable that is a regex logical-or separated aggregate of the individual country codes. So you have
String country1 = ...
String country2 = ...
String countryN = ...
String countryCodes = String.join("|", country1, country2, countryN);
then you have something along the lines of:
if (WebUI.getUrl().matches("https://www.netflix.com/" + countryCodes + "/login")) {
... do stuff
}

masking of email address in java

I am trying to mask email address with "*" but I am bad at regex.
input : nileshxyzae#gmail.com
output : nil********#gmail.com
My code is
String maskedEmail = email.replaceAll("(?<=.{3}).(?=[^#]*?.#)", "*");
but its giving me output nil*******e#gmail.com I am not getting whats getting wrong here. Why last character is not converted?
Also can someone explain meaning all these regex
Your look-ahead (?=[^#]*?.#) requires at least 1 character to be there in front of # (see the dot before #).
If you remove it, you will get all the expected symbols replaced:
(?<=.{3}).(?=[^#]*?#)
Here is the regex demo (replace with *).
However, the regex is not a proper regex for the task. You need a regex that will match each character after the first 3 characters up to the first #:
(^[^#]{3}|(?!^)\G)[^#]
See another regex demo, replace with $1*. Here, [^#] matches any character that is not #, so we do not match addresses like abc#example.com. Only those emails will be masked that have 4+ characters in the username part.
See IDEONE demo:
String s = "nileshkemse#gmail.com";
System.out.println(s.replaceAll("(^[^#]{3}|(?!^)\\G)[^#]", "$1*"));
If you're bad at regular expressions, don't use them :) I don't know if you've ever heard the quote:
Some people, when confronted with a problem, think
"I know, I'll use regular expressions." Now they have two problems.
(source)
You might get a working regular expression here, but will you understand it today? tomorrow? in six months' time? And will your colleagues?
An easy alternative is using a StringBuilder, and I'd argue that it's a lot more straightforward to understand what is going on here:
StringBuilder sb = new StringBuilder(email);
for (int i = 3; i < sb.length() && sb.charAt(i) != '#'; ++i) {
sb.setCharAt(i, '*');
}
email = sb.toString();
"Starting at the third character, replace the characters with a * until you reach the end of the string or #."
(You don't even need to use StringBuilder: you could simply manipulate the elements of email.toCharArray(), then construct a new string at the end).
Of course, this doesn't work correctly for email addresses where the local part is shorter than 3 characters - it would actually then mask the domain.
Your Look-ahead is kind of complicated. Try this code :
public static void main(String... args) throws Exception {
String s = "nileshkemse#gmail.com";
s= s.replaceAll("(?<=.{3}).(?=.*#)", "*");
System.out.println(s);
}
O/P :
nil********#gmail.com
I like this one because I just want to hide 4 characters, it also dynamically decrease the hidden chars to 2 if the email address is too short:
public static String maskEmailAddress(final String email) {
final String mask = "*****";
final int at = email.indexOf("#");
if (at > 2) {
final int maskLen = Math.min(Math.max(at / 2, 2), 4);
final int start = (at - maskLen) / 2;
return email.substring(0, start) + mask.substring(0, maskLen) + email.substring(start + maskLen);
}
return email;
}
Sample outputs:
my.email#gmail.com > my****il#gmail.com
info#mail.com > i**o#mail.com
//In Kotlin
val email = "nileshkemse#gmail.com"
val maskedEmail = email.replace(Regex("(?<=.{3}).(?=.*#)"), "*")
public static string GetMaskedEmail(string emailAddress)
{
string _emailToMask = emailAddress;
try
{
if (!string.IsNullOrEmpty(emailAddress))
{
var _splitEmail = emailAddress.Split(Char.Parse("#"));
var _user = _splitEmail[0];
var _domain = _splitEmail[1];
if (_user.Length > 3)
{
var _maskedUser = _user.Substring(0, 3) + new String(Char.Parse("*"), _user.Length - 3);
_emailToMask = _maskedUser + "#" + _domain;
}
else
{
_emailToMask = new String(Char.Parse("*"), _user.Length) + "#" + _domain;
}
}
}
catch (Exception) { }
return _emailToMask;
}

Cleaning a file name in Java

I want to write a script that will clean my .mp3 files.
I was able to write a few line that change the name but I want to write an automatic script that will erase all the undesired characters $%_!?7 and etc. while changing the name in the next format Artist space dash Song.
File file = new File("C://Users//nikita//Desktop//$%#Artis8t_-_35&Son5g.mp3");
String Original = file.toString();
String New = "Code to change 'Original' to 'Artist - Song'";
File file2 = new File("C://Users//nikita//Desktop//" + New + ".mp3");
file.renameTo(file2);
I feel like I should make a list with all possible characters and then run the String through this list and erase all of the listed characters but I am not sure how to do it.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
Edit 1:
When I try using the method remove, it still doesn't change the name.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
System.out.println("Original: " + test);
test.replace( "[0-9]%#&\\$", "");
System.out.println("New: " + test);
The code above returns the following output
Original: $%$#Arti56st_-_54^So65ng.mp3
New: $%$#Arti56st_-_54^So65ng.mp3
I'd suggest something like this:
public static String santizeFilename(String original){
Pattern p = Pattern.compile("(.*)-(.*)\\.mp3");
Matcher m = p.matcher(original);
if (m.matches()){
String artist = m.group(1).replaceAll("[^a-zA-Z ]", "");
String song = m.group(2).replaceAll("[^a-zA-Z ]", "");
return String.format("%s - %s", artist, song);
}
else {
throw new IllegalArgumentException("Failed to match filename : "+original);
}
}
(Edit - changed whitelist regex to exclude digits and underscores)
Two points in particular - when sanitizing strings, it's a good idea to whitelist permitted characters, rather than blacklisting the ones you want to exclude, so you won't be surprised by edge cases later. (You may want a less restrictive whitelist than I've used here, but it's easy to vary)
It's also a good idea to handle the case that the filename doesn't match the expected pattern. If your code comes across something other than an MP3, how would you like it to respond? Here I've through an exception, so the calling code can catch and handle that appropriately.
String new = original.replace( "[0-9]%#&\\$", "")
this should replace almost all the characters you don't want
or you can come up with your own regex
https://docs.oracle.com/javase/tutorial/essential/regex/

Dynamically replace part in URL using Regex

I tried searching for something similar, and couldn't find anything. I'm having difficulty trying to replace a few characters after a specific part in a URL.
Here is the URL: https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
I want to remove the /v/ part, leave the t1.0-9, and also remove the /s130x130/.I cannot just replace s130x130, because those may be different variables. How do I go about doing that?
I have a previous URL where I am using this code:
if (pictureUri.indexOf("&url=") != -1)
{
String replacement = "";
String url = pictureUri.replaceAll("&", "/");
String result = url.replaceAll("().*?(/url=)",
"$1" + replacement + "$2");
String pictureUrl = null;
if (result.startsWith("/url="))
{
pictureUrl = result.replace("/url=", "");
}
}
Can I do something similar with the above URL?
With the regex
/v/|/s\d+x\d+/
replaced with
/
It turns the string from
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
to
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t1.0-9/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
as seen here. Is this what you're trying to do?

Categories

Resources