I have to create a Regex for password validation which match
eg.
abcdABCD1234$%^
password must contains atleast two lowercase,two uppercase, two numeric and two special character. But they can give more than this criteria
Note- pattern should be inorder.
String pattern="(?=.*[a-z]{2,})(?=.*[A-Z]{2,})(?=.*[0-9]{2,})(?=.*[##$%&]{2,})";
it is working for me but it is not checking order
means
AB uppercase or anycharacter should not come before ab (lowercase).
Does it clear for u.
String minNum="4";
String max="20";
String REGEX="(^(?!.*(d))(?=.*[a-z]{3,})(?=.*[A-Z]{2,})(?=.*[0-9]{3,})(?=.[##$%&*><?+]{2,})^(?!.*(#r)).{"+minNum+","+max+"})";
//String regex="(?=.*[a-z]{2,})(?=.*[A-Z]{2,})(?=.*[0-9]{2,})(?=.*[##$%&]{2,})";
String INPUT ="acABC1333323##";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
System.out.println(m.matches());
it is working correctly but when i am changing password
"ABac1333323##"; it also matches but it is in correct according to my requirement, because AB is first order.
To require the characters to be in a special order is the weirdest password requirement I have ever heard and I can not believe that your customer really wants this.
Stated this I can explain your regex to you.
The lookahead assertions (the (?=...) stuff), you are using in your regex, are normally used, when the required characters can be in any order. If you really don't have this requirement, then your regex is simple, you just need to skip your lookaheads.
This will match your requirements:
String pattern="[a-z]{2,}[A-Z]{2,}[0-9]{2,}[##$%&]{2,}";
Just in case you want to allow all letters, digits and all other characters in your passwords, use Unicode code properties:
String pattern="p{Ll}{2,}p{Lu}{2,}\d{2,}[^\p{L}\d]{2,}";
I think this is what you want
(?=[a-z]{2,}).{2,}(?=[A-Z]{2,}).{2,}(?=\d{2,}).{2,}(?=[##$%&]{2,}).{2,}
It matches abcdABCD1234$%^ and abABcdCD1234$%^
It does not match ABababcdCD1234$%^ or ABac1333323##
For two or more lower case followed by two or more upper case followed by two or more digits followed by two or more special characters, use :
[a-z]{2,}[A-Z]{2,}\d{2,}[##$%&]{2,}
Maybe it could help you:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PwdValidator{
private Matcher match;
private Pattern pattern;
private static final String PWD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,20})";
public PwdValidator(){
pattern = Pattern.compile(PWD_PATTERN);
}
public boolean validate(final String pwd){
match = pattern.matcher(pwd);
return match.matches();
}
}
Related
I have strings like "(C,D) (E,F) (G,H) (J,K)" and "(C,D) (E,F) (G,H) (J,K)" or "((C,D) (E,F) (G,H) (J,K)". How to return true if regex matches pattern like in first string (which is a one tuple or series of tuples seperated by one whitespace). I tried something like "(\([A-Z],[A-Z]\)[ |$])+?", but it does not capture the final pair of tuple. In case of 2nd and 3rd string it should return false.
Here is the problem of your regex:
(\([A-Z],[A-Z]\)[ |$])+?
^^^^^
You thought that meant "space or end of string", didn't you? It actually means "space or | or dollar sign". A lot of special characters lose their special meaning when placed inside a character class.
You should replace it with (?: |$) instead. Also, the +? at the end should be a greedy +:
(\([A-Z],[A-Z]\)(?: |$))+
Personally, I don't really like this "space or end of string" thing. I would prefer repeating the tuple pattern (especially when the repeated pattern is not long):
(?:\([A-Z],[A-Z]\) )*(?:\([A-Z],[A-Z]\))
Needless to say, you should match with matches, not find.
If you want to match a string of parenthesised pairs of comma-separated capital letters, with a single space between each pair, you could use a pattern like this:
^\\([A-Z],[A-Z]\\)( \\([A-Z],[A-Z]\\))*$
That is: letter,comma,letter all in parentheses, following by zero or more occurrences of the similar parenthetic expressions, each preceded by a space.
I guess, you might be able to do that with:
\s*|\(([^()\r\n]+)\)
If the pattern would not return an empty string, would be false.
RegEx Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "\\([^()\\r\\n]+\\)|\\s*";
final String string = "(C,D) (E,F) (G,H) (J,K)\n"
+ "(C,D) (E,F) (G,H) (J,K)\n"
+ "((C,D) (E,F) (G,H) (J,K)";
final String subst = "";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
Output
(
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
Source
Regular expression to match balanced parentheses
I'm pretty new to regular expressions, and i don't really know how to use them correctly yet.
As input i have a string, in which i want to look for a certain pattern, let's say a word enclosed in !, like this: "Hello, my name is !John!". Now i want to replace the substring inside with something different. How do i look for the substring without knowing what is inside?
String str = "I don't !know! how to do this";
str = str.replace("!placeholder!", "X");
Just like that.
str.replaceAll("!.*!", "X") would be a way to do it. There are however many different "placeholders" and special characters you should be aware of (at least to escape them). In this instance I used . to match any character and * to signify that I want any number of those. The expression then reads as "replace all exclamation points, followed by any number of characters and ending in another exclamation point with the letter X".
That would also replace the exclamation points, so perhaps you want to write str.replaceAll("!.*!", "!X!"). Or maybe you don't want to replace the string "!!" so you'd use "!.+!". But to explore all the possibilities, you should really read some tutorial like this one: https://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Maybe,
!\w+!\s*
or,
!\w+!
might simply work OK for those examples.
Demo
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "!\\w+!\\s*";
final String string = "I don't !know! how to do this\n"
+ "Hello, my name is !John! ";
final String subst = "something_else ";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
Output
I don't something_else how to do this
Hello, my name is something_else
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
Objective: for a given term, I want to check if that term exist at the start of the word. For example if the term is 't'. then in the sentance:
"This is the difficult one Thats it"
I want it to return "true" because of :
This, the, Thats
so consider:
public class HelloWorld{
public static void main(String []args){
String term = "t";
String regex = "/\\b"+term+"[^\\b]*?\\b/gi";
String str = "This is the difficult one Thats it";
System.out.println(str.matches(regex));
}
}
I am getting following Exception:
Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal/unsupported escape sequence near index 7
/\bt[^\b]*?\b/gi
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.escape(Pattern.java:2416)
at java.util.regex.Pattern.range(Pattern.java:2577)
at java.util.regex.Pattern.clazz(Pattern.java:2507)
at java.util.regex.Pattern.sequence(Pattern.java:2030)
at java.util.regex.Pattern.expr(Pattern.java:1964)
at java.util.regex.Pattern.compile(Pattern.java:1665)
at java.util.regex.Pattern.<init>(Pattern.java:1337)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at java.util.regex.Pattern.matches(Pattern.java:1128)
at java.lang.String.matches(String.java:2063)
at HelloWorld.main(HelloWorld.java:8)
Also the following does not work:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String term = "t";
String regex = "\\b"+term+"gi";
//String regex = ".";
System.out.println(regex);
String str = "This is the difficult one Thats it";
System.out.println(str.matches(regex));
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
System.out.println(m.find());
}
}
Example:
{ This , one, Two, Those, Thanks }
for words This Two Those Thanks; result should be true.
Thanks
Since you're using the Java regex engine, you need to write the expressions in a way Java understands. That means removing trailing and leading slashes and adding flags as (?<flags>) at the beginning of the expression.
Thus you'd need this instead:
String regex = "(?i)\\b"+term+".*?\\b"
Have a look at regular-expressions.info/java.html for more information. A comparison of supported features can be found here (just as an entry point): regular-expressions.info/refbasic.html
In Java we don't surround regex with / so instead of "/regex/flags" we just write regex. If you want to add flags you can do it with (?flags) syntax and place it in regex at position from which flag should apply, for instance a(?i)a will be able to find aa and aA but not Aa because flag was added after first a.
You can also compile your regex into Pattern like this
Pattern pattern = Pattern.compile(regex, flags);
where regex is String (again not enclosed with /) and flag is integer build from constants from Pattern like Pattern.DOTALL or when you need more flags you can use Pattern.CASE_INSENSITIVE|Pattern.MULTILINE.
Next thing which may confuse you is matches method. Most people are mistaken by its name, because they assume that it will try to check if it can find in string element which can be matched by regex, but in reality, it checks if entire string can be matched by regex.
What you seem to want is mechanism to test of some regex can be found at least once in string. In that case you may either
add .* at start and end of your regex to let other characters which are not part of element you want to find be matched by regex engine, but this way matches must iterate over entire string
use Matcher object build from Pattern (representing your regex), and use its find() method, which will iterate until it finds match for regex, or will find end of string. I prefer this approach because it will not need to iterate over entire string, but will stop when match will be found.
So your code could look like
String str = "This is the difficult one Thats it";
String term = "t";
Pattern pattern = Pattern.compile("\\b"+term, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.find());
In case your term could contain some regex special characters but you want regex engine to treat them as normal characters you need to make sure that they will be escaped. To do this you can use Pattern.quote method which will add all necessary escapes for you, so instead of
Pattern pattern = Pattern.compile("\\b"+term, Pattern.CASE_INSENSITIVE);
for safety you should use
Pattern pattern = Pattern.compile("\\b"+Pattern.quote(term), Pattern.CASE_INSENSITIVE);
String regex = "(?i)\\b"+term;
In Java, the modifiers must be inserted between "(?" and ")" and there is a variant for turning them off again: "(?-" and ")".
For finding all words beginning with "T" or "t", you may want to use Matcher's find method repeatedly. If you just need the offset, Matcher's start method returns the offset.
If you need to match the full word, use
String regex = "(?i)\\b"+term + "\\w*";
String str = "This is the difficult one Thats it";
String term = "t";
Pattern pattern = Pattern.compile("^[+"+term+"].*",Pattern.CASE_INSENSITIVE);
String[] strings = str.split(" ");
for (String s : strings) {
if (pattern.matcher(s).matches()) {
System.out.println(s+"-->"+true);
} else {
System.out.println(s+"-->"+false);
}
}
I have a one liner string that looks like this:
My db objects are db.main_flow_tbl, 'main_flow_audit_tbl',
main_request_seq and MAIN_SUBFLOW_TBL.
I want to use regular expressions to return database tables that start with main but do not contain words audit or seq, and irrespective of the case. So in the above example strings main_flow_tbl and MAIN_SUBFLOW_TBL shall return. Can someone help me with this please?
Here is a fully regex based solution:
public static void main(String[] args) throws Exception {
final String in = "My db objects are db.main_flow_tbl, 'main_flow_audit_tbl', main_request_seq and MAIN_SUBFLOW_TBL.";
final Pattern pat = Pattern.compile("main_(?!\\w*?(?:audit|seq))\\w++", Pattern.CASE_INSENSITIVE);
final Matcher m = pat.matcher(in);
while(m.find()) {
System.out.println(m.group());
}
}
Output:
main_flow_tbl
MAIN_SUBFLOW_TBL
This assumes that table names can only contain A-Za-Z_ which \w is the shorthand for.
Pattern breakdown:
main_ is the liternal "main" that you want tables to start with
(?!\\w*?(?:audit|seq)) is a negative lookahead (not followed by) which takes any number of \w characters (lazily) followed by either "audit" or "seq". This excludes tables names that contain those sequences.
\\w++ consume any table characters possesively.
EDIT
OP's comment they may contain numbers as well
In this case use this pattern:
main_(?![\\d\\w]*?(?:audit|seq))[\\d\\w]++
i.e. use [\\d\\w] rather than \\w
String str
while ((str.startsWith("main"))&&!str.contains("audit")||!str.contains("seq")){
//your code here
}
If the string matches
^main_(\w_)*(?!(?:audit|seq))
it should be what you want...
I want to remove special characters like:
- + ^ . : ,
from an String using Java.
That depends on what you define as special characters, but try replaceAll(...):
String result = yourString.replaceAll("[-+.^:,]","");
Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".
Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).
So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):
String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");
If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").
A third way could be something like this, if you can exactly define what should be left in your string:
String result = yourString.replaceAll("[^\\w\\s]","");
This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.
Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.
Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:
String result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");
The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.
Additional information on Unicode
Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.
This will replace all the characters except alphanumeric
replaceAll("[^A-Za-z0-9]","");
As described here
http://developer.android.com/reference/java/util/regex/Pattern.html
Patterns are compiled regular expressions. In many cases, convenience methods such as String.matches, String.replaceAll and String.split will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
public class RegularExpressionTest {
public static void main(String[] args) {
System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$##!#$%^&*()("));
System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}
public static String getOnlyDigits(String s) {
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
public static String getOnlyStrings(String s) {
Pattern pattern = Pattern.compile("[^a-z A-Z]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
}
Result
String is = one
Number is = 9196390097
Try replaceAll() method of the String class.
BTW here is the method, return type and parameters.
public String replaceAll(String regex,
String replacement)
Example:
String str = "Hello +-^ my + - friends ^ ^^-- ^^^ +!";
str = str.replaceAll("[-+^]*", "");
It should remove all the {'^', '+', '-'} chars that you wanted to remove!
To Remove Special character
String t2 = "!##$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
Use the String.replaceAll() method in Java.
replaceAll should be good enough for your problem.
You can remove single char as follows:
String str="+919595354336";
String result = str.replaceAll("\\\\+","");
System.out.println(result);
OUTPUT:
919595354336
If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.
myString.replaceAll(Pattern.quote(matchingStr), replacementStr)