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

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".

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);

Regular expression is not working with single character

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.

Writing regex for string containing no only numbers

I need to write a regex containing not only digits [0-9]. How can I do that without explicitly specifying all possible charaters in a group. Is it possible to do through lookahead/lookbehind? Examples:
034987694 - doesn't match
23984576s9879 - match
rtfsdbhkjdfg - match
=-0io[-09uhidkbf - match
9347659837564983467 - doesn't match
^(?!\\d+$).*$
This should do it for you.See demo.
https://regex101.com/r/fM9lY3/1
The negative will lookahead will check if the string doesnt have integers from start to end.You need $ to make sure the check is till end or else it will just check at the start.
If you just need to detect whether the string is not numbers-only, then you can simply test for /\D/ - "succeed if there is a non-digit anywhere".
Why not check if it only contains digits, if not it matches
String[] strings = {"034987694", "23984576s9879",
"rtfsdbhkjdfg",
"=-0io[-09uhidkbf",
"9347659837564983467"};
for (String s : strings) {
System.out.printf("%s = %s%n", s, !s.matches("\\d*"));
}
output
034987694 = false
23984576s9879 = true
rtfsdbhkjdfg = true
=-0io[-09uhidkbf = true
9347659837564983467 = false
You may try the below,
string.matches(".*\\D.*");
This expects atleast 1 non-digit character.

Help in writing a Regular expression for a string

Hi please help me out in getting regular expression for the
following requirement
I have string type as
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
String sStr = "Every 1 form(s) - Earth: (Air,Fire) ";
from these strings after using regex I need to get values as "Air,Earth,Water sea,Fire" and "Air,Fire"
that means after
String vStrRegex ="Air,Earth,Water sea,Fire";
String sStrRegex ="Air,Fire";
All the strings that are input will be seperated by ":" and values needed are inside brackets always
Thanks
The regular expression would be something like this:
: \((.*?)\)
Spelt out:
Pattern p = Pattern.compile(": \\((.*?)\\)");
Matcher m = p.matcher(vStr);
// ...
String result = m.group(1);
This will capture the content of the parentheses as the first capture group.
Try the following:
\((.*)\)\s*$
The ending $ is important, otherwise you'll accidentally match the "(s)".
If you have each string separately, try this expression: \(([^\(]*)\)\s*$
This would get you the content of the last pair of brackets, as group 1.
If the strings are concatenated by : try to split them first.
Ask yourself if you really need a regex. Does the text you need always appear within the last two parentheses? If so, you can keep it simple and use substring instead:
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
int lastOpeningParens = vStr.lastIndexOf('(');
int lastClosingParens = vStr.lastIndexOf(')');
String text = vStr.substring(lastOpeningParens + 1, lastClosingParens);
This is much more readable than a regex.
I assume that there are only whitespace characters between : and the opening bracket (:
Pattern regex = Pattern.compile(":\\s+\\((.+)\\)");
You'll find your results in capturing group 1.
Try this regex:
.*\((.*)\)
$1 will contain the required string

Match any word but two in specific

I'm trying to create a regular expresion to match any word ( \w+ ) except true or false.
This is what I got so far is: \w+\s*=\s*[^true|^false]\w+
class Ntnf {
public static void main ( String ... args ) {
System.out.println( args[0].matches("\\w+\\s*=\\s*[^true|^false]\\w+") );
}
}
But is not working for:
a = b
a = true
a = false
It matches always.
How can I match any word ( \w+ ) except true or false?
EDIT
I'm trying to spot this pattern:
a = b
x = y
name = someothername
etc = xyz
x = truea
n = falsea
But avoid matching
a = true
etc = false
name = true
You can use:
^(?!(true|false)$)
^ - beginning of string
?! - negative lookahead
$ - end of string
So it matches as long as the whole string isn't just "true" or "false". Note that it can still start with one of those.
However, it may be more straightforward to use regular string comparisons.
EDIT:
The whole regex (without escaping) for your situation is:
^\w+\s*=\s*(?!(true|false)$)\w+$
It's the same idea, except that we're putting it in the equation form.
[^true] Is a character class. It only matches one character. [^true] means: "Match this character only if it not one of t, r, u or e". This is not what you need, right?
Regex is not a good idea for this task. It will be quite complicated to do it in regex. Just use string comparison.
Square brackets match a list of possible characters, or reject a list of possible characters (not necessarily in the order you specify), so [^true] is not the way to go.
When I'm trying not to match a certain word, I usually do the following:
([^t]|t[^r]|tr[^u]|tru[^e])

Categories