How to replace a part of email address using regex? - java

I want to replace a part of email address using regex. How to do it ?
For example : An email address test.email+alex#gmail.com is there and I want to replace the part of that email address from + to before # with '' so that final string will be test.email#gmail.com.
I tried with this given below :
str.replaceAll("[^+[a-z]]","");

You can try with that:
\+[^#]*
Explanation:
\+ matches + where \ is the escape character
[^#]* matches anything until it reaches #, where * means zero or more
The code is given below:
final String string = "test.email+alex#gmail.com";
final Pattern pattern = Pattern.compile("\\+[^#]*");
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll("");
Regex Test Case

If you want to match either a dot or a plus sign till an #, you could use a positive lookahead to assert an # on the right for both cases and list each option using an alternation.
(?:\.|\+[^#]*)(?=.*#)
Explanation
(?: Non capture group
\. Match a dot
| Or
\+[^#]* Match + and 0+ times any char except a dot
) Close group
(?=.*#) Positive lookahead, assert an # to the right
Regex demo | Java demo
In Java
str.replaceAll("(?:\\.|\\+[^#]*)(?=.*#)","")

Related

How to match forward slashes or periods at end of String but Not Capture Using Java Regular Expression

I am having problems understand how regular expression can match text but not include the matched text that is found. Perhaps I need to be working with groups which I'm not doing because I usually see the term non-capturing groups being used.
The goal is say I have ticket in a log file as follows:
TICKET/A/ADMIN/05MAR2020// to return only A/ADMIN/05MAR2020
or if
TICKET/A/ENGINEERING/05MAR2020. to return only A/ENGINEERING/05MAR02020
where the "//" or "." has been removed
Lastly to ignore lines like:
TICKET HAS BEEN COMPLETED
using regex = "(?<=^TICKET\\s{0,2}/).*(?://|\\.)?
So telling parser look for TICKET at start of string followed by a forward slash, but don't return TICKET. And look for either a double forward slash "//" or "." a period at the end of string but make this optional.
My Java 1.8.x code follows:
// used in the import statement: import java.util.regex.Matcher;
// import java.util.regex.Pattern;
private static void testRegex() {
String ticket1 = "TICKET/A/ITSUPPORT/05MAR2020//";
String ticket2 = "TICKET /B/ADMIN/06MAR2020.";
String ticket3 = "TICKET/C/GENERAL/07MAR2020";
//https://www.regular-expressions.info/brackets.html
String regex = "(?<=^TICKET\\s{0,2}/).*(?://|\\.)?";
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(ticket1);
if (mat.find()) {
String myticket = ticket1.substring(mat.start(), mat.end());
System.out.println(myticket+ ", Expect 'A/ITSUPPORT/05MAR2020'");
}
mat = pat.matcher(ticket2);
if (mat.find()) {
String myticket = ticket2.substring(mat.start(), mat.end());
System.out.println(myticket+", Expect 'B/ADMIN/06MAR2020'");
}
mat = pat.matcher(ticket3);
if (mat.find()) {
String myticket = ticket3.substring(mat.start(), mat.end());
System.out.println(myticket+", Expect 'C/GENERAL/07MAR2020'");
}
regex = "(//|\\.)";
pat = Pattern.compile(regex);
mat = pat.matcher(ticket1);
if (mat.find()) {
String myticket = ticket1.substring(mat.start(), mat.end());
System.out.println(myticket+", "+mat.start() + ", " + mat.end() + ", " + mat.groupCount());
}
}
My actual results follow:
A/ITSUPPORT/05MAR2020//, Expect 'A/ITSUPPORT/05MAR2020
B/ADMIN/06MAR2020., Expect 'B/ADMIN/06MAR2020
C/GENERAL/07MAR2020, Expect 'C/GENERAL/07MAR2020
//, 28, 30, 1
Any suggestion would be appreciate. Please note, been learning from StackOverflow long-time but first entry, hope question is asked appropriately. Thank you.
You could use a positive lookahead at the end of the pattern instead of a match.
The lookahead asserts what is at the end of the string is an optional // or .
As the dot and the double forward slash are optional, you have to make the .*? non greedy.
(?<=^TICKET\s{0,2}/).*?(?=(?://|\.)?$)
In parts
(?<= Positive lookbehind, assert what is on the left is
^ Start of the string
TICKET\s{0,2}/ Match TICKET and 0-2 whitespace chars followed by /
) Close lookbehind
.*? Match any char except a newline 0+ times, as least as possible (non greedy)
(?= Positive lookahead, assert what is on the the right is
(?: Non capture group for the alternation | because both can be followed by $
// Match 2 forward slashes
| Or
\. Match a dot
)? Close the non capture group and make it optional
$ Assert the end of the string
) Close the positive lookahead
In Java
String regex = "(?<=^TICKET\\s{0,2}/).*?(?=(?://|\\.)?$)";
Regex demo 1 | Java demo
1. The regex demo has Javascript selected for the demo only
Output of the updated pattern with your code:
A/ITSUPPORT/05MAR2020, Expect 'A/ITSUPPORT/05MAR2020'
B/ADMIN/06MAR2020, Expect 'B/ADMIN/06MAR2020'
C/GENERAL/07MAR2020, Expect 'C/GENERAL/07MAR2020'
//, 28, 30, 1

Extract sub-string from given String value using regex

I have a requirement where a string needs to be matched and then extract further value from a that string
I will receive a header in request whose value will be a DN name from ssl certificate. Here need to match a specific string 1.2.3.47 in the header and extract remaining text.
Sample String passed to method:
O=ABC Bank Plc/1.2.3.47=ABC12-PQR-121878, CN=7ltM2wQ3bqlDJdBEURGAMq, L=INDIA, C=INDIA, E=xyz#gmail.com
Here is my code:
private String extractDN(String dnHeader) {
if(!ValidatorUtil.isEmpty(dnHeader)){
String tokens[]=dnHeader.split(",");
if(tokens[0].contains("1.2.3.47")){
int index=tokens[0].lastIndexOf("1.2.3.47");
String id=tokens[0].substring(index+9);
System.out.println(id);
}
}
return id;
}
Can a regex pattern be used here to match and extract value? Is there any better way to achieve this? Please help.
If you want to use a pattern and if you know that the value always starts with a forward slash and if followed by one or more digits separated by a dot and then an equals sign, you could use a capturing group:
/[0-9](?:\\.[0-9]+)+=([^,]+)
/ Match /
[0-9]+ Match 1+ digit 0-9
(?: Non capturing group
\\.[0-9]+ match . and 1+ digits 0-9
)+ Close non capturing group and repeat 1+ times
= Match =
([^,]+) Capture group 1, match 1+ times any char except a ,
Regex demo | Java demo
For example
final String regex = "/[0-9]+(?:\\.[0-9]+)+=([^,]+)";
final String string = "O=ABC Bank Plc/1.2.3.47=ABC12-PQR-121878, CN=7ltM2wQ3bqlDJdBEURGAMq, L=INDIA, C=INDIA, E=xyz#gmail.com";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
ABC12-PQR-121878
If you want a more precise match, you could also specify the start of the pattern:
\\bO=\\w+(?:\\h+\\w+)*/[0-9]+(?:\\.[0-9]+)+=([^,]+)
Regex demo

How do get value between () in java string just before .?

I have to replace file name abc(1).jpg to abc(2).jpg . Here is the code
String example = "my attachements with some name (56).jpg";
Matcher m = Pattern.compile("\\((\\d{1,}).\\)").matcher(example);
int a = 0;
while(m.find()) {
a=Integer.parseInt(m.group(1));
String p = example.replace(String.valueOf(a), String.valueOf(a+1));
}
It is working fien as per given use case . But fails in case of abc(ab)(1)(ab).jpg for this case it just changed to abc(ab)(2)(ab).jpg . Which is not required . So how do i can verify that numeric bracket is just before dot i.e .
You may use
String example = "my attachements with some name (56).jpg";
Matcher m = Pattern.compile("(?<=\\()\\d+(?=\\)\\.)").matcher(example);
example = m.replaceAll(r -> String.valueOf(Integer.parseInt(m.group())+1) );
System.out.println( example );
// => my attachements with some name (57).jpg
See the Java demo. The regex used is
(?<=\()\d+(?=\)\.)
See the regex demo. It matches
(?<=\() - a location immediately preceded with (
\d+ - then consumes 1+ digits
(?=\)\.) - immediately followed with ). char sequence.
If you need to tell the regex to match the dot that is the last dot in the string (where it is most likely the extension delimiter) replace (?=\)\.) with (?=\)\.[^.]*$). See this regex demo.
You can use a lookahead regex for this:
"\\((\\d+)\\)(?=\\.)"
(?=\.) is a lookahead condition that asserts presence of dot right after closing )
RegEx Demo

RegEx for capturing special chars

I am trying to replace a string using regular expression what i need basically is to convert a code like assignment:
k*=i
into
k=k+i
In my example:
jregex.Pattern p=new jregex.Pattern("([a-z]|[A-Z])([a-z]|[A-Z]|\\d)*[\\+|\\*|\\-|\\/][=]([a-z]|[A-Z])*([a-z]|[A-Z]|\\d)");
Replacer r= new Replacer(p,"1=$1,2=$2,3=$3,4=$4,5=$5,6=$6,7=$7,8=$8");
String result=r.replace("k*=i");
The regex seems to not extract the special chars.
(in this example: +, -, *, /, =)
So what I get as result is:
1=k,2=,3=,4=i,5=,6=,7=,8=
(I can extract only the k & i)
How do I solve this problem?
Here, we can design as expression similar to:
(.+)[*+-/]=(.+)
where we are capturing our k and i using these two capturing groups in the start and end:
(.+)
We can add more boundaries, if we wish, such as start and end char:
^(.+)[*+-/]=(.+)$
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(.+)[*+-/]=(.+)";
final String string = "k*=i\n"
+ "apple*=orange";
final String subst = "$1=$1+$2";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
DEMO
RegEx Circuit
jex.im visualizes regular expressions:
You could use 3 capturing groups and capturing *+/- in a character class.
([a-zA-Z])([*+/-])=([a-zA-Z])
That will match:
([a-zA-Z]) Capture group 1, match a-z A-Z
([*+/-]) Capture group 2, match * + / -
= Match literally
([a-zA-Z]) Capture group 3, match a-z A-Z
Regex demo | Java demo
And replace with:
$1=$1$2$3

How do we replace below 'x' sub string with 'y' sub string using regex in Java?

[![enter image description here][1]][1]I want to replace substring src="/slm/attachment/63338424306/Note.jpg" with substring jira/rally/images using regular expression in Java.
Below is the query to get the list of the String which contains substring src="/slm/attachment/63338424306/Note.jpg"
criteria.add(Restrictions.like("comment", "%<img%"));
criteria.setMaxResults(1);
List<Comments> list = criteria.list();
How can i replace using regex? Please help me here.
Let's say xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpgxxxxxxxx is the string then after the replacement I am expecting xxxxxxxxsrc="jira/rally/images/Note.jpgxxxxxxxx
the no. 63338424306 can be any random no.
image name & format 'Note.jpg' can be changed i.e. 'abc.png' etc.
Basically, I want to replace /slm/attachment/63338424306/ with jira/rally/images
Thanks to all of you for your answers. I have updated the question little bit, please help me with that.
yourString.replaceAll("src=\"/slm/attachment", "src=\"/jira/rally/images");
You could use a capturing group for the src=" part and match the part that you want to replace.
(src\s*=\s*")/slm/attachment/\d+
( Capture group
src\s*=\s*" Match src, 0+ whitespace chars, =, 0+ whitespace chars and "
) Close group
/slm/attachment/ Match literally
\d+ Match 1+ digits
Note that if you want to match 0+ spaces only and no newlines, you could use a space only or [ \t]* to match a space and tab instead of \s*
In Java
String regex = "(src\\s*=\\s*\")/slm/attachment/\\d+";
And use the first capturing group in the replacement:
$1jira/rally/images
Result:
src="jira/rally/images/Note.jpg
Regex demo | Java demo
For example:
String string = "src = \"/slm/attachment/63338424306/Note.jpg";
System.out.println(string.replaceAll("(src\\s*=\\s*\")/slm/attachment/\\d+", "$1jira/rally/images"));
// src = "jira/rally/images/Note.jpg
You can use the following replacement sequences:
String a = "abc 123 src=\"/slm/attachment/63338424306/Note.jpg abc 132";
String b = "abc 123 src=\"/slm/attachment/61118424306/Note.jpg xyz";
String c = "123xxsrc=\"/slm/attachment/51238424306/Note.jpgxx324";
System.out.println(a.replaceAll("(?<=src=\")/slm/attachment/\\d+","jira/rally/images"));
System.out.println(b.replaceAll("(?<=src=\")/slm/attachment/\\d+","jira/rally/images"));
System.out.println(c.replaceAll("(?<=src=\")/slm/attachment/\\d+","jira/rally/images"));
output:
abc 123 src="jira/rally/images/Note.jpg abc 132
abc 123 src="jira/rally/images/Note.jpg xyz
123xxsrc="jira/rally/images/Note.jpgxx324
regex demo: https://regex101.com/r/ZtRg49/7/

Categories