I am trying to generalise Regex-java like if I give value and pattern than the method should return true or false if the given value matches the given pattern - TRUE else FALSE.
following is the method I tried with simple Alphanumeric
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static boolean isValidInput(String value, String pattern) {
boolean isValid = false;
Pattern walletInputPattern = Pattern.compile(pattern);
Matcher walletMatcher = walletInputPattern.matcher(value);
if (walletMatcher.matches()) {
isValid = true;
}
return isValid;
}
public static void main(String args[]) {
String pattern = "^[a-zA-Z0-9]*$";
String inputValue = "45645";
if (isValidInput(inputValue, pattern)) {
System.out.println("Alphanumeric");
} else {
System.out.println("OOPS");
}
}
}
but I gave wrong input and still it prints the TRUE..
what is the mistake I do here....??..
thanks for your inputs and spending your valuable time :)
I believe this lookahead-based regex should work for you:
String pattern = "^(?=.*?[A-Za-z])(?=.*?[0-9])[a-zA-Z0-9]+$";
This ensures that:
There is at least one alphabetic character in the input
There is at least one digit in the input
The input is comprised of ONLY alphanumerics
It is the right result because 45645 is indeed an alphanumeric value.
If you want to make sure the value is a combination of numbers and letters then you need a different expression:
String pattern = "^(?!^[0-9]+$)(?!^[a-zA-Z]+$)[a-zA-Z0-9]+$";
(?!^[0-9]+$): This makes sure the string isn't just a combination of digits.
(?!^[a-zA-Z]+$): This makes sure the string isn't just a combination of letters.
[a-zA-Z0-9]*: This matches a combination of letters and digits.
Related
I tried this:
private static void isLetterandNumberCombo(Tokens token) {
if (token.getContents().matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")){
token.setValid(false);
}
}
but the input 123f45 still does not set the token to valid as I thought it would
Your solution is fine. You just need to add the case-insensitive flag ((?i)) to match lowercase letters. And matches() looks for a full match, so you don't need the anchors at the beginning and end:
(?i)(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+
Give this a whirl
private static boolean isLetterandNumberCombo(Tokens token) {
String regex = "^[a-zA-Z0-9]+$";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(token.getContents()).matches();
}
You'll get back true or false if the token is valid.
I would go with:
^[A-Za-z\d]*(([A-Za-z]\d)|(\d[A-Za-z]))[A-Za-z\d]*$
The idea is that a valid string will have either a letter followed by a number or the opposite somewhere, and other optional letters or numbers before or after.
A simple regex would do the job:
Change your function to:
private static void isLetterandNumberCombo(Tokens token) {
token.setValid(token.getContents() != null && token.getContents().matches("[a-zA-Z0-9]+"));
}
How to check whether a string is present on another string in Java, but here the conditions be like:
For Example:
String 1: Panda
String 2: "a1d22n333a4444p"
Here String 2 needs to have the letter 'p','n','d' at-least once and 'a' at-least twice. Pattern should be matches with the above conditions.
I have done with Regular Expression, but i am not getting the solution.
public static boolean isContainsAnimal(String message,String animal) {
String animalPattern=generatePattern("panda");
Pattern pattern = Pattern.compile(animalPattern);
Matcher matcher = pattern.matcher(message);
int count = 0;
while (matcher.find()) {
count++;
}
if(count>=1){
return true;
}else
{
return false;
}
}
public static String generatePattern(String animal){
String result="";
for(int i=0;i<animal.length();i++){
result+="[^"+animal.charAt(i)+"]*"+animal.charAt(i);
}
return result;
}
Suggest me a solution for this problem.
Your attempt does not take account of the different possible orderings of the characters in the animal string. In fact, for a 5 distinct character string, there are 5 factorial different orders.
It is possible to generate a regex with all of the orderings as alternates, but the result is ... horrible and inefficient.
A better idea is to work out if there are letters (like 'a') are repeated. Then generate a regex for each letter, use "match" to apply each one and AND the results.
An even better idea is to not use regexes at all. They are the wrong tool for this job.
I'm trying to write a Java method that will determine (true or false) if a particular String matches a regex of animal<L_OPERAND,R_OPERAND>, where L_OPERAND can be any of the following values: dog, cat, sheep and R_OPERAND can be any one of the following values: red, blue. All values are case- and whitespace-sensitive.
Some examples:
animal<fizz,cat> => false; fizz is not a valid L_OPERAND value
animAl<dog,blue> => false; animAl contains an upper-case char (illegal)
animal<dog,sheep> => false; sheep is not a valid R_OPERAND value
animal<dog, blue> => false; contains whitespace between ',' and 'blue' (no whitesapce allowed)
animal<dog,blue> => true; valid
animal<cat,red> => true; valid
animal<sheep,blue> => true; valid
My best attempt so far:
public class RegexExperiments {
public static void main(String[] args) {
boolean b = new RegexExperiments().isValidAnimalDef("animal<dog,blue>");
System.out.println(b);
}
public boolean isValidAnimalDef(String animalDef) {
String regex = "animal<[dog,cat,sheep],[red,blue]>";
if(animalDef.matches(regex)) {
return true;
} else {
return false;
}
}
}
Although I'm not getting any exceptions, I'm getting false for every type of input string (animalDef) I pass in. So obviously my regex is bad. Can anyone spot where I'm going awry?
Your problem lies within the [dog,cat,sheep] and [red,blue] structures. [] represent a character class, it matches a single character that is contained inside. For the first one this would be ,acdeghopst and for the second ,bdelru. So you currently match strings like animal<d,b> or even animal<,,,>.
What you are after is a mix of a grouping structure and an alternation. Alternations are provided by |, so e.g. dog|cat|sheep would match dog or cat or sheep. As you want this alternation inside a larger pattern, you have to contain it inside a group. The (for this case) simpliest grouping structure is a capturing group which is starting with ( and ending with ).
Your final pattern could then be animal<(dog|cat|sheep),(red|blue)>.
Try
String regex = "animal<(dog|cat|sheep),(red|blue)>";
You can use RegEx animal<(dog|cat|sheep),(red|blue)>
Output
false
false
false
false
true
true
true
Code
import java.util.regex.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println(filterOut("animal<fizz,cat>"));
System.out.println(filterOut("animAl<dog,blue>"));
System.out.println(filterOut("animal<dog,sheep>"));
System.out.println(filterOut("animal<dog, blue>"));
System.out.println(filterOut("animal<dog,blue>"));
System.out.println(filterOut("animal<cat,red>"));
System.out.println(filterOut("animal<sheep,blue>"));
}
public static boolean filterOut(String str) {
Matcher m = Pattern.compile("animal<(dog|cat|sheep),(red|blue)>").matcher(str);
if (m.find()) return true;
else return false;
}
}
Let's say a user inputs text. How does one check that the corresponding String is made up of only letters and numbers?
import java.util.Scanner;
public class StringValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your password");
String name = in.nextLine();
(inert here)
You can call matches function on the string object. Something like
str.matches("[a-zA-Z0-9]*")
This method will return true if the string only contains letters or numbers.
Tutorial on String.matches: http://www.tutorialspoint.com/java/java_string_matches.htm
Regex tester and explanation: https://regex101.com/r/kM7sB7/1
Use regular expressions :
Pattern pattern = Pattern.compile("\\p{Alnum}+");
Matcher matcher = pattern.matcher(name);
if (!matcher.matches()) {
// found invalid char
}
for loop and no regular expressions :
for (char c : name.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
// found invalid char
break;
}
}
Both methods will match upper and lowercase letters and numbers but not negative or floating point numbers
Modify the Regular expression from [a-zA-Z0-9] to ^[a-zA-Z0-9]+$
String text="abcABC983";
System.out.println(text.matches("^[a-zA-Z0-9]+$"));
Current output: true
The regular expression character class \p{Alnum} can be used in conjunction with String#matches. It is equivalent to [\p{Alpha}\p{Digit}] or [a-zA-Z0-9].
boolean allLettersAndNumbers = str.matches("\\p{Alnum}*");
// Change * to + to not accept empty String
See the Pattern documentation.
I am newbie to java regular expression. I wrote following code for validating the non digit number. If we enter any non digit number it should return false. for me the below code always return false. whats the wrong here?
package regularexpression;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumberValidator {
private static final String NUMBER_PATTERN = "\\d";
Pattern pattern;
public NumberValidator() {
pattern = Pattern.compile(NUMBER_PATTERN);
}
public boolean validate(String line){
Matcher matcher = pattern.matcher(line);
return matcher.matches();
}
public static void main(String[] args) {
NumberValidator validator = new NumberValidator();
boolean validate = validator.validate("123");
System.out.println("validate:: "+validate);
}
}
From Java documentation:
The matches method attempts to match the entire input sequence against the pattern.
Your regular expression matches a single digit, not a number. Add + after \\d to matchone or more digits:
private static final String NUMBER_PATTERN = "\\d+";
As a side note, you can combine initialization and declaration of pattern, making the constructor unnecessary:
Pattern pattern = Pattern.compile(NUMBER_PATTERN);
matches "returns true if, and only if, the entire region sequence matches this matcher's pattern."
The string is 3 digits, which doesn't match the pattern \d, meaning 'a digit'.
Instead you want the pattern \d+, meaning 'one or more digits.' This is expressed in a string as "\\d+"