Java - How to test if a String contains both letters and numbers - java

I need a regex which will satisfy both conditions.
It should give me true only when a String contains both A-Z and 0-9.
Here's what I've tried:
if PNo[0].matches("^[A-Z0-9]+$")
It does not work.

I suspect that the regex below is slowed down by the look-around, but it should work regardless:
.matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")
The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.

It easier to write and read if you use two separate regular expressions:
String s = "blah-FOO-test-1-2-3";
String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";
if (s.matches(numRegex) && s.matches(alphaRegex)) {
System.out.println("Valid: " + input);
}
Better yet, write a method:
public boolean isValid(String s) {
String n = ".*[0-9].*";
String a = ".*[A-Z].*";
return s.matches(n) && s.matches(a);
}

A letter may be either before or after the digit, so this expression should work:
(([A-Z].*[0-9])|([0-9].*[A-Z]))
Here is a code example that uses this expression:
Pattern p = Pattern.compile("(([A-Z].*[0-9])|([0-9].*[A-Z]))");
Matcher m = p.matcher("AXD123");
boolean b = m.find();
System.out.println(b);

Here is the regex for you
Basics:
Match in the current line of string: .
Match 0 or any amount of any characters: *
Match anything in the current line: .*
Match any character in the set (range) of characters: [start-end]
Match one of the regex from a group: (regex1|regex2|regex3)
Note that the start and end comes from ASCII order and the start must be before end. For example you can do [0-Z], but not [Z-0]. Here is the ASCII chart for your reference
Check the string against regex
Simply call yourString.matches(theRegexAsString)
Check if string contains letters:
Check if there is a letter: yourString.matches(".*[a-zA-Z].*")
Check if there is a lower cased letter: yourString.matches(".*[a-z].*")
Check if there is a upper cased letter: yourString.matches(".*[A-Z].*")
Check if string contains numbers:
yourString.matches(".*[0-9].*")
Check if string contains both number and letter:
The simplest way is to match twice with letters and numbers
yourString.matches(".*[a-zA-Z].*") && yourString.matches(".*[0-9].*")
If you prefer to match everything all together, the regex will be something like: Match a string which at someplace has a character and then there is a number afterwards in any position, or the other way around. So your regex will be:
yourString.matches(".*([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z]).*")
Extra regex for your reference:
Check if the string stars with letter
yourString.matches("[a-zA-Z].*")
Check if the string ends with number
yourString.matches(".*[0-9]")

This should solve your problem:
^([A-Z]+[0-9][A-Z0-9]*)|([0-9]+[A-Z][A-Z0-9]*)$
But it's unreadable. I would suggest to first check input with "^[A-Z0-9]+$", then check with "[A-Z]" to ensure it contains at least one letter then check with "[0-9]" to ensure it contains at least one digit. This way you can add new restrictions easily and code will remain readable.

What about ([A-Z].*[0-9]+)|([0-9].*[A-Z]+) ?

Try using (([A-Z]+[0-9])|([0-9]+[A-Z])) .It should solve.

use this method:
private boolean isValid(String str)
{
String Regex_combination_of_letters_and_numbers = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$";
String Regex_just_letters = "^(?=.*[a-zA-Z])[a-zA-Z]+$";
String Regex_just_numbers = "^(?=.*[0-9])[0-9]+$";
String Regex_just_specialcharachters = "^(?=.*[##$%^&+=])[##$%^&+=]+$";
String Regex_combination_of_letters_and_specialcharachters = "^(?=.*[a-zA-Z])(?=.*[##$%^&+=])[a-zA-Z##$%^&+=]+$";
String Regex_combination_of_numbers_and_specialcharachters = "^(?=.*[0-9])(?=.*[##$%^&+=])[0-9##$%^&+=]+$";
String Regex_combination_of_letters_and_numbers_and_specialcharachters = "^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[##$%^&+=])[a-zA-Z0-9##$%^&+=]+$";
if(str.matches(Regex_combination_of_letters_and_numbers))
return true;
if(str.matches(Regex_just_letters))
return true;
if(str.matches(Regex_just_numbers))
return true;
if(str.matches(Regex_just_specialcharachters))
return true;
if(str.matches(Regex_combination_of_letters_and_specialcharachters))
return true;
if(str.matches(Regex_combination_of_numbers_and_specialcharachters))
return true;
if(str.matches(Regex_combination_of_letters_and_numbers_and_specialcharachters))
return true;
return false;
}
You can delete some conditions according to your taste

Related

Print a part of string that made a string match regex

I want to check if my String contains any letters(N S W E - map directions). And if it does I want to set direction = that letter and return either true or false.
Example:
input:
15.15.15 N
output I want to receive:
N
output that direction = matcher.group(); gives me:
15.15.15 N
As expected it prints string that matched the regex. I want to print only the part that made it matched. Letter can be at beginning or at the end of the string. Any idea how to make it?
public boolean example (String value) {
Pattern parrent = Pattern.compile(".*[a-zA-Z].*");
Matcher matcher = parrent.matcher(value);
if(matcher.find()) {
direction = matcher.group();
System.out.println("direction" + direction);
return false;
}
else
return true;
}
You don't have a group there!
Try this here instead:
Pattern pattern = Pattern.compile(".* (N|S|W|E)");
The point is: you basically have
non-whitespace whatever
a space
one of four letters which you are interested in.
Thus you want a simple pattern that ignores anything you don't care about; and groups around the element you want back.

Replacing Strings with a number in it without a for loop

So I currently have this code;
for (int i = 1; i <= this.max; i++) {
in = in.replace("{place" + i + "}", this.getUser(i)); // Get the place of a user.
}
Which works well, but I would like to just keep it simple (using Pattern matching)
so I used this code to check if it matches;
System.out.println(StringUtil.matches("{place5}", "\\{place\\d\\}"));
StringUtil's matches;
public static boolean matches(String string, String regex) {
if (string == null || regex == null) return false;
Pattern compiledPattern = Pattern.compile(regex);
return compiledPattern.matcher(string).matches();
}
Which returns true, then comes the next part I need help with, replacing the {place5} so I can parse the number. I could replace "{place" and "}", but what if there were multiple of those in a string ("{place5} {username}"), then I can't do that anymore, as far as I'm aware, if you know if there is a simple way to do that then please let me know, if not I can just stick with the for-loop.
then comes the next part I need help with, replacing the {place5} so I can parse the number
In order to obtain the number after {place, you can use
s = s.replaceAll(".*\\{place(\\d+)}.*", "$1");
The regex matches arbitrary number of characters before the string we are searching for, then {place, then we match and capture 1 or more digits with (\d+), and then we match the rest of the string with .*. Note that if the string has newline symbols, you should append (?s) at the beginning of the pattern. $1 in the replacement pattern "restores" the value we need.

Check if string contains any non digit character - no libraries - Java

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.

Use regex to replace sequences in a string with modified characters

I am trying to solve a codingbat problem using regular expressions whether it works on the website or not.
So far, I have the following code which does not add a * between the two consecutive equal characters. Instead, it just bulldozes over them and replaces them with a set string.
public String pairStar(String str) {
Pattern pattern = Pattern.compile("([a-z])\\1", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if(matcher.find())
matcher.replaceAll(str);//this is where I don't know what to do
return str;
}
I want to know how I could keep using regex and replace the whole string. If needed, I think a recursive system could help.
This works:
while(str.matches(".*(.)\\1.*")) {
str = str.replaceAll("(.)\\1", "$1*$1");
}
return str;
Explanation of the regex:
The search regex (.)\\1:
(.) means "any character" (the .) and the brackets create a group - group 1 (the first left bracket)
\\1, which in regex is \1 (a java literal String must escape a backslash with another backslash) means "the first group" - this kind of term is called a "back reference"
So together (.)\1 means "any repeated character"
The replacement regex $1*$1:
The $1 term means "the content captured as group 1"
Recursive solution:
Technically, the solution called for on that site is a recursive solution, so here is recursive implementation:
public String pairStar(String str) {
if (!str.matches(".*(.)\\1.*")) return str;
return pairStar(str.replaceAll("(.)\\1", "$1*$1"));
}
FWIW, here's a non-recursive solution:
public String pairStar(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len*2);
char last = '\0';
for (int i=0; i < len; ++i) {
char c = str.charAt(i);
if (c == last) sb.append('*');
sb.append(c);
last = c;
}
return sb.toString();
}
I dont know java, but I believe there is replace function for string in java or with regular expression. Your match string would be
([a-z])\\1
And the replace string would be
$1*$1
After some searching I think you are looking for this,
str.replaceAll("([a-z])\\1", "$1*$1").replaceAll("([a-z])\\1", "$1*$1");
This is my own solutions.
Recursive solution (which is probably more or less the solution that the problem is designed for)
public String pairStar(String str) {
if (str.length() <= 1) return str;
else return str.charAt(0) +
(str.charAt(0) == str.charAt(1) ? "*" : "") +
pairStar(str.substring(1));
}
If you want to complain about substring, then you can write a helper function pairStar(String str, int index) which does the actual recursion work.
Regex one-liner one-function-call solution
public String pairStar(String str) {
return str.replaceAll("(.)(?=\\1)", "$1*");
}
Both solution has the same spirit. They both check whether the current character is the same as the next character or not. If they are the same then insert a * between the 2 identical characters. Then we move on to check the next character. This is to produce the expected output a*a*a*a from input aaaa.
The normal regex solution of "(.)\\1" has a problem: it consumes 2 characters per match. As a result, we failed to compare whether the character after the 2nd character is the same character. The look-ahead is used to resolve this problem - it will do comparison with the next character without consuming it.
This is similar to the recursive solution, where we compare the next character str.charAt(0) == str.charAt(1), while calling the function recursively on the substring with only the current character removed pairStar(str.substring(1).

Java regex and pattern matching: finding "blanks" in pattern which do not include them?

So, I need to write a compiler scanner for a homework, and thought it'd be "elegant" to use regex. Fact is, I seldomly used them before, and it was a long time ago. So I forgot most of the stuff about them and needed to have a look around. I used them successfully for the identifiers (or at least I think so, I still need to do some further tests but for now they all look ok), but I have a problem with the numbers-recognition.
The function nextCh() reads the next character on the input (lookahead char). What I'd like to do here is to check if this char matches the regex [0-9]*. I append every matching char in the str field of my current token, then I read the int value of this field. It recognizes a single number input such as "123", but the problem I have is that for the input "123 456", the final str will be "123 456" while I should get 2 separate tokens with fields "123" and "456". Why is the " " being matched?
private void readNumber(Token t) {
t.str = "" + ch; // force conversion char --> String
final Pattern pattern = Pattern.compile("[0-9]*");
nextCh(); // get next char and check if it is a digit
Matcher match = pattern.matcher("" + ch);
while (match.find() && ch != EOF) {
t.str += ch;
nextCh();
match = pattern.matcher("" + ch);
}
t.kind = Kind.number;
try {
int value = Integer.parseInt(t.str);
t.val = value;
} catch(NumberFormatException e) {
error(t, Message.BIG_NUM, t.str);
}
Thank you!
PS: I did solve my problem using the code below. Nevertheless, I'd like to understand where the flaw is in my regex expression.
t.str = "" + ch;
nextCh(); // get next char and check if it is a number
while (ch>='0' && ch<='9') {
t.str += ch;
nextCh();
}
t.kind = Kind.number;
try {
int value = Integer.parseInt(t.str);
t.val = value;
} catch(NumberFormatException e) {
error(t, Message.BIG_NUM, t.str);
}
EDIT: turns out my regex also doesn't work for the identifiers recognition (again, includes blanks), so I had to switch to a system similar to my "solution" (while with a lot of conditions). Guess I'll need to study the regex again :O
I'm not 100% sure whether this is relevant in your case, but this:
Pattern.compile("[0-9]*");
matches zero or more numbers anywhere in the string, because of the asterisk. I think the space gets matched because it is a match for 'zero numbers'. If you wanted to make sure the char was a number, you would have to match one or more, using the plus sign:
Pattern.compile("[0-9]+");
or, since you are only comparing a single char at a time, just match one number:
Pattern.compile("^[0-9]$");
You should be using the matches method rather than the find method. From the documentation:
The matches method attempts to match the entire input sequence against the pattern
The find method scans the input sequence looking for the next subsequence that matches the pattern.
So in other words, by using find, if the string contains a digit anywhere at all, you'll get a match, but if you use matches the entire string must match the pattern.
For example, try this:
Pattern p = Pattern.compile("[0-9]*");
Matcher m123abc = p.matcher("123 abc");
System.out.println(m123abc.matches()); // prints false
System.out.println(m123abc.find()); // prints true
Use a simpler regex like
/\d+/
Where
\d means a digit
+ means one or more
In code:
final Pattern pattern = Pattern.compile("\\d+");

Categories

Resources