Regular expression is not working with single character - java

I am trying to write regular expression in Java to evaluate two strings mentioned with () separated by ,
Example: (test1,test2)
I have written below code
public static void main(String[] a){
String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+.\\)";
String test = "(test1,test2)";
System.out.println(test.matches(pattern));
}
It works as expected and prints true in below cases
String test = "(test1,test2)";
String test = "(t,test2)";
But it is printing false when I send below
String test = "(test1,t)";
It is strange because I am using same expression before and after ,
It returns true for (t,test2) but not for (test1,t)
Please let me know what am I missing in this regular expression. I need it to evaluate and return true for (test1,t)

There's no need for the . (that matches one character) in your regex. Remove . from your regex so it becomes "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)" and it should work.

Use this regex:
String pattern = "^\\(.+,.+\\)";
This will match your required strings.

In the second part of your pattern, you have "[a-zA-Z0-9]+."
If you're trying to match "t", it will see t for the [a-zA-Z0-9]+ part, but it requires another character after that to match the . part.
Revised pattern: "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)"

Delete the dot after the second group[a-zA-Z0-9]
Demo

and even simpler you can use \w for words, you can use instead of [a-zA-Z0-9]
so your regular expression would be like that
\(\w+,\w+\)

In your regular expression '.' is not needed in the latter part.
change is as "\([a-zA-Z0-9]+,[a-zA-Z0-9]+\)" so that it will be returning true for "(test,t)"
String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)";
String test = "(te,t)";
System.out.println(test.matches(pattern)); // true

String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)";
String test = "(test1,test2)";
String t1 = "(t,test2)";
String t2="(test2,t)";
System.out.println(test.matches(pattern));
System.out.println(t1.matches(pattern));
System.out.println(t2.matches(pattern));
just try this code, it will give you answer you want.
You have written "." at the end after + in your pattern so clear it.

Related

How to match two string using java Regex

String 1= abc/{ID}/plan/{ID}/planID
String 2=abc/1234/plan/456/planID
How can I match these two strings using Java regex so that it returns true? Basically {ID} can contain anything. Java regex should match abc/{anything here}/plan/{anything here}/planID
If your "{anything here}" includes nothing, you can use .*. . matches any letter, and * means that match the string with any length with the letter before, including 0 length. So .* means that "match the string with any length, composed with any letter". If {anything here} should include at least one letter, you can use +, instead of *, which means almost the same, but should match at least one letter.
My suggestion: abc/.+/plan/.+/planID
If {ID} can contain anything I assume it can also be empty.
So this regex should work :
str.matches("^abc.*plan.*planID$");
^abc at the beginning
.* Zero or more of any Character
planID$ at the end
I am just writing a small code, just check it and start making changes as per you requirement. This is working, check for your other test cases, if there is any issue please comment that test case. Specifically I am using regex, because you want to match using java regex.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MatchUsingRejex
{
public static void main(String args[])
{
// Create a pattern to be searched
Pattern pattern = Pattern.compile("abc/.+/plan/.+/planID");
// checking, Is pattern match or not
Matcher isMatch = pattern.matcher("abc/1234/plan/456/planID");
if (isMatch.find())
System.out.println("Yes");
else
System.out.println("No");
}
}
If line always starts with 'abc' and ends with 'planid' then following way will work:
String s1 = "abc/{ID}/plan/{ID}/planID";
String s2 = "abc/1234/plan/456/planID";
String pattern = "(?i)abc(?:/\\S+)+planID$";
boolean b1 = s1.matches(pattern);
boolean b2 = s2.matches(pattern);

Java. Regular Expressions. How to mix NOT with AND?

I have a string (VIN) like this:
String vin = "XTC53229R71133923";
I can use OR to see if there are characters Q,O,I:
String regExp = ".*[QOI].*";
This works.
However I can not check that any of these 3 letter are NOT in the string.
It means: (NOT Q) AND (NOT O) AND (NOT I).
I tried negative lookahead:
String regExp = "(?!.*[QOI].*)";
This doens't work. In "XTC5Q3229R71133923" it returns true.
The main issue - I have 2 conditions:
Number of characters (A-Z0-9) in the string should be 17.
The string should not have Q,O,I.
I can check this with 2 regexps:
String regExp = "^([A-Z0-9]{17})$"; //should be true
String regExp = ".*[QOI].*"; //should be false
But is there a way to combine these 2 checks in one regular expression?
How about just using a custom range that doesn't include the characters you do not want?
String regexp = "^([A-HJ-NPR-Z0-9]{17})$";
Here you go ^[^QOI]{17}$. Starting a charcter class with ^ means "do not match any of these characters".

Regex to match expression with certain number/pattern of slashes

It's probably easiest if I just give examples...
I have input data that looks like this:
/foo/blah/something/this
And some that looks like this:
/foo/blah/this
I need a regex that will match the latter but not the former.
In other words:
/foo/*/this should match
/foo/*/*/this should not match
"foo" is a static value, meaning it is always "foo" and "this" is the same. The 'blah' and 'something' represent variables that could be anything.
So, the following strings SHOULD be matched by my regex:
/foo/john/jones
/foo/james/jones
/foo/steven/jones
/foo/samantha/jones
but the following strings should NOT match:
/foo/john/paul/jones
/foo/james/earl/jones
/foo/steven/james/jones
/foo/samantha/wilson/jones
Any help?
^/foo/[^/]+/[^/]+$
You can replace [^/]+ with [^/]* if you want stuff like /foo//jones to work as well.
You can use regex for this and also the matches method of the string class to match the strings:
sample:
String[] s = {"/foo/john/jones", "/foo/james/jones", "/foo/john/paul/jones", "/foo/james/earl/jones"};
for(String s2 : s)
System.out.println(s2.matches("/foo/([^/]+)/jones"));
result:
true
true
false
false
You can use this regex:
^/\w+/\w+/\w+$
Working demo
Thanks Pshemo for the comment. I forgot to mention that for java you need to escape backslashes and / doesn't need to be escaped.
So, the java regex would be:
^/\\w+/\\w+/\\w+$
By the way, a nice Pschemo observation is that if you have /foo as static value. You could use this regex:
^/foo/\\w+/\\w+$
You can also do this without a regex:
public boolean isValid(String expression) {
if (!expression.startsWith("/foo/") {
return false;
}
String[] parts = expression.split("/");
// note: four including the empty string before the first slash
return parts.length == 4;
}

Java regex and .matches()

I'm trying to match a String with a regular expression in Java.
If I define the regular expression to match a digit like this:
private static final String NUMERIC_CHARS = "[0-9]";
The line below returns false where test = 12345678
test.matches(NUMERIC_CHARS);
I was expecting this to be true. According to oracle docs matches() returns "true if, and only if, the entire region sequence matches this matcher's pattern". Is this not the case here?
Thanks in advance for your help.
You are missing anchor + (to match more than 1 digit), so use this regex:
"[0-9]+"
Your java code:
private static final String NUMERIC_CHARS = "[0-9]+";
Your current regex only allows 1 digit. Modify it as follows:
private static final String NUMERIC_CHARS = "^[0-9]+$";
Then it will evaluate to true.

Remove parenthesis from String using java regex

I want to remove parenthesis using Java regular expression but I faced to error No group 1 please see my code and help me.
public String find_parenthesis(String Expr){
String s;
String ss;
Pattern p = Pattern.compile("\\(.+?\\)");
Matcher m = p.matcher(Expr);
if(m.find()){
s = m.group(1);
ss = "("+s+")";
Expr = Expr.replaceAll(ss, s);
return find_parenthesis(Expr);
}
else
return Expr;
}
and it is my main:
public static void main(String args[]){
Calculator c1 = new Calculator();
String s = "(4+5)+6";
System.out.println(s);
s = c1.find_parenthesis(s);
System.out.println(s);
}
The simplest method is to just remove all parentheses from the string, regardless of whether they are balanced or not.
String replaced = "(4+5)+6".replaceAll("[()]", "");
Correctly handling the balancing requires parsing (or truly ugly REs that only match to a limited depth, or “cleverness” with repeated regular expression substitutions). For most cases, such complexity is overkill; the simplest thing that could possibly work is good enough.
What you want is this: s = s.replaceAll("[()]","");
For more on regex, visit regex tutorial.
You're getting the error because your regex doesn't have any groups, but I suggest you use this much simpler, one-line approach:
expr = expr.replaceAll("\\((.+?)\\)", "$1");
You can't do this with a regex at all. It won't remove the matching parentheses, just the first left and the first right, and then you won't be able to get the correct result from the expression. You need a parser for expressions. Have a look around for recursive descent ezpresssion parsers, the Dijkstra shunting-yard algorithm, etc.
The regular expression defines a character class consisting of any whitespace character (\s, which is escaped as \s because we're passing in a String), a dash (escaped because a dash means something special in the context of character classes), and parentheses. Try it working code.
phoneNumber.replaceAll("[\\s\\-()]", "");
I know I'm very late here. But, just in case you're still looking for a better answer. If you want to remove both open and close parenthesis from a string, you can use a very simple method like this:
String s = "(4+5)+6";
s=s.replaceAll("\\(", "").replaceAll("\\)","");
If you are using this:
s=s.replaceAll("()", "");
you are instructing the code to look for () which is not present in your string. Instead you should try to remove the parenthesis separately.
To explain in detail, consider the below code:
String s = "(4+5)+6";
String s1=s.replaceAll("\\(", "").replaceAll("\\)","");
System.out.println(s1);
String s2 = s.replaceAll("()", "");
System.out.println(s2);
The output for this code will be:
4+5+6
(4+5)+6
Also, use replaceAll only if you are in need of a regex. In other cases, replace works just fine. See below:
String s = "(4+5)+6";
String s1=s.replace("(", "").replace(")","");
Output:
4+5+6
Hope this helps!

Categories