I want to validate a string which donot have numeric characters.
If my string is "javaABC" then it must be validated
If my string is "java1" then it must not be validated
I want to restrict all the integers.
Try this:
String Text = ...;
boolean HasNoNumber = Text.matches("^[^0-9]*$");
'^[^0-9]*$' = From Start(^) to end ($), there are ([...]) only non(^) number(0-9). You can use '\D' as other suggest too ... but this is easy to understand.
See more info here.
You can use this:
\D
"\D" matches non-digit characters.
Here is one way that you can search for a digit in a String:
public boolean isValid(String stringToValidate) {
if(Pattern.compile("[0-9]").matcher(stringToValidate).find()) {
// The string is not valid.
return false;
}
// The string is valid.
return true;
}
More detail is here:
http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html
The easiest to understand is probably matching for a single digit and if found fail, instead of creating a regexp that makes sure that all characters in the string are non-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]+"));
}
I need to check whether my string follows a particular pattern or not. My string will always start with text_data_ and then followed by a number always as shown below
text_data_123
text_data_124
text_data_126
text_data_127
text_data_128
Now how can I check whether the string I am getting is in above format:
String value = getData();
// but this doesn't work?
if(value.matches("text_data(?<=_)\\d+")) {
// found a match
}
What's wrong I am doing?
The lookbehind does not assert that what immediately precedes the current position is _.
You don't need to use lookbehind for this.
if(value.matches("text_data_\\d+")) { ... }
using 'startsWith(String prefix)' method in String Class.
if (value.startsWith("text_data_")) {
// found a match
}
You could use:
If(value.contains("text_data_")){
}
But I would suggest using dreaming cat's solution.
This might be clear to someone familiar with regex expressions but I am not.
Example:
String onlyNumbers = "1233444";
String numbersAndDigits = "123344FF";
if (IS_ONLY_NUMBERS(onlyNumbers))
return true;
if (IS_ONLY_NUMBERS(numbersAndDigits))
return false;
Suggestions? Is there a way to do a similar check without importing libraries?
Try using String.matches("\\d+"). If that statement returns false, then there are characters in your string that are not digits. \d means the character must be a digit, and the + means that every character must be a digit.
Like so:
String onlynumbers = "1233444";
String numbersanddigits = "123344FF";
System.out.println(onlynumbers.matches("\\d+")); // prints "true"
System.out.println(numbersanddigits.matches("\\d+")); // prints "false"
You can try with:
if (onlynumbers.matches("[0-9]+")
return true;
if (numbersanddigits.matches("[0-9]+")
return false;
Also, as a shortcut, you can use \\d+ instead of [0-9]+. It's just a matter of choice which one to pick.
I want to match certain group of characters in a String independent of their order in the String using regex fucntion. However, the only requirement is that they all must be there.
I have tried
String elD = "15672";
String t = "12";
if ((elD.matches(".*[" + t + "].*"))) {
System.out.println(elD);
}
This one checks whether any of the characters are present. But I want all of them to be there.
Also I tried
String elD = "15672";
String t = "12";
if ((elD.matches(".*(" + t + ").*"))) {
System.out.println(elD);
}
This does not work as well. I have searched quite a while but I could not find an example when all of the characters from the pattern must be present in the String independent of their order.
Thanks
You can write regex for this but it would not look nice. If you would want to check if your string contains anywhere x and y you would need to use few times look-ahead like
^(?=.*x)(?=.*y).*$
and use it like
yourStirng.matches(regex);
But this way you would need to create your own method which would generate you dynamic regex and add (?=.*X) for each character you want to check. You would also need to make sure that this character is not special in regex like ? or +.
Simpler and not less effective solution would be creating your own method which would check if your string contains all searched characters, something like
public static boolean containsUnordered(String input, String searchFor){
char[] characters = searchFor.toCharArray();
for (char c: characters)
if (!input.contains(String.valueOf(c)))
return false;
return true;
}
You can built a pattern from the search string using the replaceAll method:
String s = "12";
String pattern = s.replaceAll("(.)", "(?=[^$1]*$1)");
Note: You can't test the same character several times. (i.e. 112 gives (?=[^1]*1)(?=[^1]*1)(?=[^2]*2) that is exactly the same as (?=[^1]*1)(?=[^2]*2))
But in my opinion Pshemo method is probably more efficient.
Greetings,
I am developing GWT application where user can enter his details in Japanese.
But the 'userid' and 'password' should only contain English characters(Latin Alphabet).
How to validate Strings for this?
You can use String#matches() with a bit regex for this. Latin characters are covered by \w.
So this should do:
boolean valid = input.matches("\\w+");
This by the way also covers numbers and the underscore _. Not sure if that harms. Else you can just use [A-Za-z]+ instead.
If you want to cover diacritical characters as well (ä, é, ò, and so on, those are per definition also Latin characters), then you need to normalize them first and get rid of the diacritical marks before matching, simply because there's no (documented) regex which covers diacriticals.
String clean = Normalizer.normalize(input, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
boolean valid = clean.matches("\\w+");
Update: there's an undocumented regex in Java which covers diacriticals as well, the \p{L}.
boolean valid = input.matches("\\p{L}+");
Above works at Java 1.6.
public static boolean isValidISOLatin1 (String s) {
return Charset.forName("US-ASCII").newEncoder().canEncode(s);
} // or "ISO-8859-1" for ISO Latin 1
For reference, see the documentation on Charset.
There is my solution and it is working excellent
public static boolean isStringContainsLatinCharactersOnly(final String iStringToCheck)
{
return iStringToCheck.matches("^[a-zA-Z0-9.]+$");
}
There might be a better approach, but you could load a collection with whatever you deem to be acceptable characters, and then check each character in the username/password field against that collection.
Pseudo:
foreach (character in username)
{
if !allowedCharacters.contains(character)
{
throw exception
}
}
For something this simple, I'd use a regular expression.
private static final Pattern p = Pattern.compile("\\p{Alpha}+");
static boolean isValid(String input) {
Matcher m = p.matcher(input);
return m.matches();
}
There are other pre-defined classes like \w that might work better.
I successfully used a combination of the answers of user232624, Joachim Sauer and Tvaroh:
static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII"); // or "ISO-8859-1" for ISO Latin 1
boolean isValid(String input) {
return Character.isLetter(ch) && asciiEncoder.canEncode(username);
}