I have seen Mail services displays the email id's as e*****e#gmail.com , mostly in their recovery page.
So i am trying to replace the example#gmail.com as e*****e#gmail.com .
Is it possible to achieve it using String#replace(String) alone ? or should i use some REGEX to achieve it .
Thanks for your valuable suggestions in adavance
Search regex:
\b(\w)\S*?(\S)(?=#)(\S+)\b
Replacement Pattern:
$1****$2$3****$4
RegEx Demo
Code:
String email = "anexample#gmail.com";
String repl = email.replaceFirst("\\b(\\w)\\S*?(\\S#)(\\S)\\S*(\\S\\.\\S*)\\b",
"$1****$2$3****$4");
//=> a****e#g****l.com
You can try without regex too
String email = "example#gmail.com";
int start = 1;
int end = email.indexOf("#") - 1;
StringBuilder sb = new StringBuilder(email);
StringBuilder sb1=new StringBuilder();
for(int i=start;i<end;i++){
sb1.append("*");
}
sb.replace(start, end, sb1.toString());
System.out.println(sb.toString());
Out put:
e*****e#gmail.com
It could be possible through replaceAll function.
(?<!^).(?=.*?.#)
Use the above regex and replace the matched characters with *
DEMO
String s = "example#gmail.com";
System.out.println(s.replaceAll("(?<!^).(?=.*?.#)", "*"));
Output:
e*****e#gmail.com
Update:
Use the below regex to get the output like e*****e#g***l.com
String s = "example#gmail.com";
System.out.println(s.replaceAll("\\B.\\B(?=.*?\\.)", "*"));
Output:
e*****e#g***l.com
I sugges to use indexOf and substring. With replace you can run into tuble with emails like gmail#gmail.com
Related
String: [img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Result I Want: [img border=0]images/bbcode/sets/misc/bullet_go.png[/img] without /scm/ text.
Issue: Text scm is not static, could be any other text in data.
What I want: Have a look to this string
[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Regex which can fetch a text between ] and images/bbcode/ so the regex will detect the \scm\ text and then can remove this \scm\ from String data and end result will look like
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
PS: I am implementing this logic in Java.
you can reach the goal without using regex, too.
since you said that the other parts are static, try this:
String myStr = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
myStr = "[img border=0]" + myStr.substring(myStr.indexOf("images"));
System.out.println(myStr);
and the output will be:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
I have captured text between '] and /images..' and replace this text with "". Check the following demo:
String s = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
s = s.replaceAll("(?<=])/[^/]+/","");
System.out.println(s);
if [img border=0] dynamic, you can take all except /scm/
some demo
String input = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
Pattern p = Pattern.compile("(^.*\\])\\/.*?\\/(.*$)");
Matcher m = p.matcher(input);
if (m.find()) {
String output = m.replaceFirst("$1$2");
System.out.println(output);
}
// -> [img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
I found one more way to solve this same problem
String pattereString = "].*/images";
String maineString = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
maineString = maineString.replaceAll(pattereString, "images");
System.out.println(maineString);
Output:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}
i need to read a file upto certain comma,for example;
String s=hii,lol,wow,and,finally
need output as hii,lol,wow,and
Dont want last comma followed with characters
As my code is reading last comma string
Example:iam getting my code out put as: finally
Below is my code
please guide me
File file =new File("C:/Users/xyz.txt");
FileInputStream inputStream = new FileInputStream(file);
String filke = IOUtils.toString(inputStream);
String[] pieces = filke.split("(?=,)");
String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());
String www=answer.substring(1);
System.out.format("Answer = \"%s\"%n", www);
You don't necessarily need to use regex for this. Just get the index of the last ',' and get the substring from 0 to that index:
String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and
String in Java has a method called lastIndexOf(String str). That might come in handy for you.
Say your input is String s = "hii,lol,wow,and,finally";
You can do a String operation like:
String s = "hii,lol,wow,and,finally";
s = s.substring(0, s.lastIndexOf(","));
This gives you the output: hii,lol,wow,and
If you want to use java 8 stream to do it for you maybe try filter ?
String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());
this will print Answer = "hii,lol,wow,and"
To have stricly regex you can use the Pattern.compile and Matcher
Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}
Will match hii, lol, wow, and,
See the regex example here https://regex101.com/r/1iZDjg/1
I have this string for example:
Username: tester1tt8e677 Password: b6a492e14c
I need to get out the username and the password only.
The password and user name are dynamically changing.
What is the best way doing it with Java, and how?
Thanks.
Do yourself a massive favour and get started on regular expressions. It will take more time than blindly copy-pasting an answer, but once you grasp the concept you can solve a huge number of problems with it.
You might want to check out this tutorial, which is java-specifiy and looks quite solid. Or just go ahead and google, you will find tons of information out there.
Once again - please do learn about regular expressions. You will not regret it.
Try using a Matcher with a regex:
String pattern = "Username: (\\.+?) Password: (\\.+?)";
Matcher matcher = Pattern.compile( pattern ).matcher();
matcher.find();
You can then get your username and password from the first and second group:
String u = matcher.group(1);
String p = matcher.group(2);
However this does not sound like a good way to do whatever you are doing and you might want to consider another approach.
You could use substring:
String String1 = "Username: testter1tt8e677";
System.out.println(String1.substring(0,10));
This should return "Username:"
So:
System.out.println(String1.substring(10));
returns "testter1tt8e677".
Try with below code:
String s1 = "Username:tester1tt8e677 Password:b6a492e14c";
// splitting String
String[] splitString = s1.split(" ");
for (String sp: splitString) {
// Again Splitting
String[] s2 = sp.split(":");
System.out.println(s2[1]);
}
Rather than think of how you can work your solution around your problem, see if it can be broken up.
What do we want to do? We want to get values out of a String.
How? Rather than removing what we don't want, let's take out what we do want.
You then make the solution a lot simpler for yourself.
str = "Username: tester1tt8e677 Password: b6a492e14c";
String[] splitStrings = str.split("\\s+");
System.out.println(splitStrings[1]); //Username
System.out.println(splitStrings[3]); //Password
String str="Username: tester1tt8e677 Password: b6a492e14c";
System.out.println(str.substring(0,str.indexOf(" ", str.indexOf(" ") + 1)).split(": ")[1]);
System.out.println(str.substring(str.indexOf(" ", str.indexOf(" ") + 1)+1,str.length()).split(": ")[1]);
Output:
tester1tt8e677
b6a492e14c
Well I have found my answer and it was pretty easy:
StringBuilder pass1 = new StringBuilder(pass).delete(0, 35);
String resultString = pass1.toString();
StringBuilder user1 = new StringBuilder(user).delete(0, 10);
StringBuilder user2 = new StringBuilder(user1).delete(14, 35);
String resultString = user2.toString();
Thanks anyway (-:
I have String user#domain:port
I want to fetch user, domain and port from this String.
So I created regex:
public static final String MATCH_USER_DOMAIN_PORT = "^([0-9,a-zA-Z-.*_]+)#([a-z0-9]+[\\.-][a-z0-9]+\\.[a-z]{2,}+):(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3})$";
and this is my method in Unitest so far:
public void test____matchesUserDomainWithPort(){
String identityText = "maxim#domain.com:5555";
String user = "";
String domain = "";
String port = "";
if(identityText.matches(MATCH_USER_DOMAIN_PORT))
{
Pattern p = Pattern.compile(MATCH_USER_DOMAIN_PORT);
Matcher m = p.matcher(identityText);
user = m.group(1);
domain= m.group(2);
port= m.group(3);
}
assertEquals("maxim", user);
assertEquals("domain.com", domain);
assertEquals("5555", port);
}
I get error:
java.lang.IllegalStateException: No successful match so far
at java.util.regex.Matcher.ensureMatch(Matcher.java:607)
....
in row: user = m.group(1);
I opened http://gskinner.com/RegExr/?2v5r0
and there all seems good:
Output:
RegExp: /^([0-9,a-zA-Z-.*_]+#[a-z0-9]+([\.-][a-z0-9]+)*)+\.[a-z]{2,}+:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3})$/
pattern: ^([0-9,a-zA-Z-.*_]+#[a-z0-9]+([\.-][a-z0-9]+)*)+\.[a-z]{2,}+:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3})$
flags:
3 capturing groups:
group 1: ([0-9,a-zA-Z-.*_]+#[a-z0-9]+([\.-][a-z0-9]+)*)
group 2: ([\.-][a-z0-9]+)
group 3: (6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3})
Do I miss something?
in C i just write: sscanf(identityText,"%[^#]#%[^:]:%511s",user,domain,port);
For sure I can split this text with # and : and get 3 values, but its interesting how to do that in gentle form :)
Please, help
Please use
if(identityText.matches(MATCH_USER_DOMAIN_PORT)){
Pattern p = Pattern.compile(MATCH_USER_DOMAIN_PORT);
Matcher m = p.matcher(identityText);
while(m.find()){
user = m.group(1);
domain= m.group(2);
port= m.group(3);
}
}
thanks
Yes, I think your regex is wrong.
public static final String MATCH_USER_DOMAIN_PORT = "^([0-9,a-zA-Z-.*_]+#[a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}+:(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3})$";
To break it down:
^(
[0-9,a-zA-Z-.*_]+
any number of these characters, will match "maxim"
#
will match "#"
[a-z0-9]+
any number of these characters, will match "domain"
([\\.-][a-z0-9]+)*
will match ".com" (or theoretically ".somethingelse.com", nice)
)+
will make group #2 "maxim#domain.com", I believe, but what's with the "+" ?
\\.
nothing in the input string here
[a-z]{2,}+
is this for a country code like .eu ? Again, what's with the "+" ?
:
(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3})
seems overly complicated - probably don't do the numeric validation with the regex
$
Take a look at Using a regular expression to validate an email address for some advice on validation of email addresses.