Issue with regex - java

I want to write a regex where a string has
(9 characters) and start with either "g" or "r"
and then are all numbers afterward.
I have written this but it does not work:
public static void main(String[] args) {
String id= "g57895452";
String pattern = "/^g([0-9]+){8}$/";
if (id.matches(pattern)) {
System.out.println("true");
} else {
System.out.println("false");
}
}

Corrected re:
"^[gr]([0-9]{8})$"
You need not + when you already has {8}.
Also you don't need () when you don't want to use the group further in the code.
"^[gr][0-9]{8}$"

Remove the / from start and end of your regex pattern, It will work.

Related

Regex max a string till " and not stop at \"

I have a String to be checked for regex :
"field":"Testing, for something \"and something\""
which I want to pattern match and replace with :
"field":"SAFE"
For this, I am trying to pattern match and capture till the last inverted commas. I have tried the following regex, but its not matching :
Pattern p = Pattern.compile("\"field\":\".*?(?!\\\")\"");
New to regex, can anyone suggest what I might be doing wrong? Thanks!
EDIT :
I guess the question was not clear. Apologies. The above is not the end of the string. It can contain more fields in succession :
"field":"Testing, for something \"and something\"", "new_field":"blahblah", ...
output should be :
"field":"SAFE", "new_field":"blahblah", ...
You can do it as follows:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\"";
str = str.replaceAll("(\"field\":).*", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE"
Explanation:
(\"field\":) is the first capturing group
.* specifies all characters
$1 specifies the first capturing group
Update:
Writing this update based on the clarification from OP.
You can use positive lookahead for comma as shown below:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\", \"new_field\":\"blahblah\"";
str = str.replaceAll("(\"field\":).*(?=,)", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE", "new_field":"blahblah"
Here is an example.
$str = '"field":"Testing, for something \"and something\""';
echo preg_replace('/(\"field\":\")(.*)(\")/i', "$1SAFE$3", $str);
Regex is tested: here.

Regular expression to remove specific characters in email addresses

Im trying to figure out how i can remove certain characters in an email address before the domain name using nothing but a simple regex and replaceAll in Java.
In email addresses,
Need to remove any number of . before #<domain name>
Also remove anything between + up to # but not including #. For instance in joebloggs+123#domain.com should be joebloggs#domain.com.
So far I have,
class Main {
public static void main(String[] args) {
String matchingRegex = "(\\.|(\\+.*(?=#)))";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
}
}
which replaces everything including the domain name.
joebloggs#gmailcom
What i really need is joebloggs#gmail.com.
Can this be achieved with regex alone ?
Another look ahead did the trick in the end.
class Main {
public static void main(String[] args) {
String matchingRegex = "((\\.+)(?=.*#)|(\\+.*(?=#)))";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joebloggs+123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123+456#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joebloggs#gmail.com".replaceAll(matchingRegex, ""));
System.out.println("joe.bloggs.123+456.789#gmail.com".replaceAll(matchingRegex, ""));
}
}
Results in,
joebloggs#gmail.com
joebloggs#gmail.com
joebloggs#gmail.com
joebloggs123#gmail.com
joebloggs123#gmail.com
joebloggs#gmail.com
joebloggs123#gmail.com
You could try spliting the string (the email) on the # and running replaceAll on the the first half and then put the strings back together.
Check out: How to split a string in Java
For splitting strings.
Try this regex [.](?=.*#)|(?=\\+)(.*)(?=#). It looks up dots up to # (even if there's text in between), or everything from + up to #. Hope it helps https://regex101.com/r/gyUpta/1
class Main {
public static void main(String[] args) {
String matchingRegex = "[.](?=.*#)|(?=\\+)(.*)(?=#)";
System.out.println("joe.bloggs+123#gmail.com".replaceAll(matchingRegex, ""));
}
}
This will do the trick...
public static void main(String args[]) {
String matchingRegex = "(\\.|(\\+.*(?=#)))";
String email = "joe.bloggs+123#gmail.com";
String user = email.substring(0, email.indexOf("#")+1);
String domain = email.substring(email.indexOf("#")+1);
System.out.println(user.replaceAll(matchingRegex, "") + domain);
}
This is the easiest way I have found to do it.
String address = "joe.bloggs+123#gmail.com";
int at = address.indexOf("#");
address = address.substring(0, at).replaceAll("\\.|\\+.*", "")
+ address.substring(at);
System.out.println(address);
if you try to split for regex sorry i don't remember java this example is in javascript
let string = "joe.bloggs+123#gmail.com"
//firts the function
function splitString(params) {
return params.split(/\+(.)+\#/)
}
//second the concat
let list = splitString(string)
// the first element+the las element
console.log(`${list[0]}${list[list.length -1]}`)

Java Regex How to Find if String Contains Characters but order is not a matter

I have String like this "abcdefgh"
I want to check the string contains the following characters [fcb]
Condition is : The string must contain all characters in any order.
How to write a regex for this one.
I tried following regexes :
.*[fcb].* ---> In this case it not check all characters. If any one character matchs it will return true
Don't use regex. Just use String.contains to test for each of the characters in turn:
in.contains("f") && in.contains("c") && in.contains("b")
You could get the char arry and sort it. Afterwards you could check if it contains .*b.*c.*f.*.
public static boolean contains(String input) {
char[] inputChars = input.toCharArray();
Arrays.sort(inputChars);
String bufferInput = String.valueOf(inputChars);
// Since it is sorted this will check if it simply contains `b,c and f`.
return bufferInput.matches(".*b.*c.*f.*");
}
public static void main(String[] args) {
System.out.println(contains("abcdefgh"));
System.out.println(contains("abdefgh"));
}
output:
true
false
this will check if all the letters are present in the string.
public class Example {
public static void main(String args[]) {
String stringA = "abcdefgh";
String opPattern = "(?=[^ ]*f)(?=[^ ]*c)(?=[^ ]*b)[^ ]+";
Pattern opPatternRegex = Pattern.compile(opPattern);
Matcher matcher = opPatternRegex.matcher(stringA);
System.out.println(matcher.find());
}
}
You can use positive lookahead for this
(?=.*b)(?=.*c)(?=.*f)
Not very efficient but easy to understand:
if (s.matches(".*b.*") && s.matches(".*c.*") && s.matches(".*f.*"))

Replace special character in a String

I have to replace a string whit special character like this: XY_Universit�-WWWWW-ZZZZZ in another one like: XY_Universita-WWWWW-ZZZZZ.
I tried solutions like stringToReplace.replaceAll(".*Universit.*", "Universita"); but it replace all the string with the word ''Universita" and it isn't what i want.
stringToReplace.replaceAll("Universit[^a]", "Universita")
public static void main(String[] args) throws IOException {
String exp = "XY_Universit�-WWWWW-ZZZZZ";
exp = exp.replaceAll("[^\\w\\s\\-_]", "");
System.out.println(exp);
}
output
XY_Universit-WWWWW-ZZZZZ
You have to be lazy :P
use : .*?XY_Universit. to select only the first XY_universit
demo here
Another odd way..
String example = "XY_Universit�-WWWWW-ZZZZZ";
char ch = 65533; //find ascii of special char
System.out.println(example.replace(ch, 'a'));

How to replace last dot in a string using a regular expression?

I'm trying to replace the last dot in a String using a regular expression.
Let's say I have the following String:
String string = "hello.world.how.are.you!";
I want to replace the last dot with an exclamation mark such that the result is:
"hello.world.how.are!you!"
I have tried various expressions using the method String.replaceAll(String, String) without any luck.
One way would be:
string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");
Alternatively you can use negative lookahead as:
string = string.replaceAll("\\.(?!.*\\.)","!");
Regex in Action
Although you can use a regex, it's sometimes best to step back and just do it the old-fashioned way. I've always been of the belief that, if you can't think of a regex to do it in about two minutes, it's probably not suited to a regex solution.
No doubt get some wonderful regex answers here. Some of them may even be readable :-)
You can use lastIndexOf to get the last occurrence and substring to build a new string: This complete program shows how:
public class testprog {
public static String morph (String s) {
int pos = s.lastIndexOf(".");
if (pos >= 0)
return s.substring(0,pos) + "!" + s.substring(pos+1);
return s;
}
public static void main(String args[]) {
System.out.println (morph("hello.world.how.are.you!"));
System.out.println (morph("no dots in here"));
System.out.println (morph(". first"));
System.out.println (morph("last ."));
}
}
The output is:
hello.world.how.are!you!
no dots in here
! first
last !
The regex you need is \\.(?=[^.]*$). the ?= is a lookahead assertion
"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")
Try this:
string = string.replaceAll("[.]$", "");

Categories