I've written a really simple regular expression to validate a phone number that I can see works in the engine provided by zytrax.com regex. When I use it in the class to compile as a pattern I get en error with the escaped characters for the Pattern.compile string to process.
package Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindMainTestExcercisePN {
private static String phone;
private static Matcher matcher;
private boolean getCheckNumber(String pn) {
boolean valid = matcher.matches();
return valid;
}
private void PhoneNumber(String input) {
Pattern pattern = Pattern.compile("^(?:(?:\\+?\\s*1\\s*(?:[.-\\s*]?)(?:[.\\s*-]?))?(?:(\\s*([0-9]|[0-9]|[0-9])\\s*)|([0-9]|[0-9]|[0-9]))\\s*(?:[.-\\s*]?)?)?([0-9]|[0-9]|[0-9]{2})\\s*(?:[.\\s*-]?)(?:[.-\\s*]?)?([0-9]|[0-9]|[0-9]|[0-9]{4})\\s*");
matcher = pattern.matcher(input);
}
public static void main(String[] a) {
FindMainTestExcercisePN ex15 = new FindMainTestExcercisePN();
phone = "1-098-234-5454";
ex15.PhoneNumber(phone);
boolean bool = ex15.getCheckNumber(phone);
System.out.println("The number is valid= " + bool);
}
}
If you take out the escapes it will work just fine (prime ex. 1-345-345-3324) so any suggestions please?
This expression is illegal:
[.-\\s*]
In a character class, the dash character is a range operator, eg [0-9] means "any character in the range 0 to 9"., but here you have coded a range .-\s, which attempts to express "any character in the range dot to 'any whitespace'", which is clearly nonsense.
To code a literal dash in a character class, code it first or last.
If the intention if this expression is "a dot, dash, whitespace or star", then code:
[.\\s*-]
If the star is not intended as a literal, but you want to express "a dot or dash, or any number of whitespace", use this:
([.-]?|\\s*)
you method getCheckNumber always return true
Related
I have a complicate string split, I need to remove the comments, spaces, and keep all the numbers but change all string into character. If the - sign is at the start and followed by a number, treat it as a negative number rather than a operator
the comment has the style of ?<space>comments<space>? (the comments is a place holder)
Input :
-122+2 ? comments ?sa b
-122+2 ? blabla ?sa b
output :
["-122","+","2","?","s","a","b"]
(all string into character and no space, no comments)
Replace the unwanted string \s*\?\s*\w+\s*(?=\?) with "". You can chain String#replaceAll to remove any remaining whitespace. Note that ?= means positive lookahead and here it means \s*\?\s*\w+\s* followed by a ?. I hope you already know that \s specifies whitespace and \w specifies a word character.
Then you can use the regex, ^-\d+|\d+|\D which means either negative integer in the beginning (i.e. ^-\d+) or digits (i.e. \d+) or a non-digit (\D).
Demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "-122+2 ? comments ?sa b";
str = str.replaceAll("\\s*\\?\\s*\\w+\\s*(?=\\?)", "").replaceAll("\\s+", "");
Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
-122
+
2
?
s
a
b
I want to replace some regex with regex in java for e.g.
Requirement:
Input: xyxyxyP
Required Output : xyzxyzxyzP
means I want to replace "(for)+\{" to "(for\{)+\{" . Is there any way to do this?
I have tried the following code
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReplaceDemo2 {
private static String REGEX = "(xy)+P";
private static String INPUT = "xyxyxyP";
private static String REGEXREPLACE = "(xyz)+P";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
// get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REGEXREPLACE);
System.out.println(INPUT);
}
}
but the output is (xyz)+P .
You can achieve it with a \G based regex:
String s = "xyxyxyP";
String pattern = "(?:(?=xy)|(?!^)\\G)xy(?=(?:xy)*P)";
System.out.println(s.replaceAll(pattern, "$0z"));
See a regex demo and an IDEONE demo.
In short, the regex matches:
(?:(?=xy)|(?!^)\\G) - either a location followed with xy ((?=xy)) or the location after the previous successful match ((?!^)\\G)
xy - a sequence of literal characters xy but only if followed with...
(?=(?:xy)*P) - zero or more sequences of xy (due to (?:xy)*) followed with a P.
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 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.
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+"