I'd like to know what I can use to check if the last characters in a string are numeric. For example for the ID: "S000123" .
I used the following to check if it starts with E, S or X.
if(! id.startsWith("E") || ! id.startsWith("S") || ! id.startsWith("X")) {
alertinputError("Incorrect format in the ID field", lineNum);
return;
}
Thanks.
You could simply use id.matches(".\\d+"). To check if id starts with E, S or X followed by a string of digits, however, you could use
id.matches("[ESX]\\d+")
Relevant Documentation
matches
I know this is a very old post but for future readers, I thought I'll add a different approach.
I personally found regex to be very unreadable (do you know someone that can write regex without using google?)
So I prefer this approach:
char lastChar = string.charAt(string.length() - 1)
return Character.isDigit();
If you want to do it for the last N letters and not just 1:
string.substring(string.length() - n).chars()
.allMatch(Character::isDigit);
A regex might work well here.
String foo = "bar123";
Pattern p = Pattern.compile(".*[0-9]+$");
Matcher m = p.matcher(foo);
if(m.matches)
System.out.println("yeah!");
So if the string is composed of any bunch of characters followed by one or more numbers, this will print "yeah!".
try this:
id.matches("^.+?\\d$")
Try it:
String id = "S000123";
Pattern pattern = Pattern.compile("[ESX][0-9].*");
Matcher matcher = pattern.matcher(id);
System.out.println(matcher.matches());
All right then you can use following Code:
boolean flag = true;
for (int i = id.length() - 1 ; i >= id.length() - 6 ; i--)
{
if (!Character.isDigit(id.charAt(i)))
{
flag = false;
break;
}
}
if (flag)
System.out.println("ID is valid");
else
System.out.println("ID is invalid");
Related
I want a regex to match a string that only has the words A,I and D without any order or sort
also:if the string has a letter thats not any of these then doesnt go into the if
I have tried with || and other symbols but still cant get it
Doesnt have to be a regex Im just trying to find a way to solve it
String message = "AIDDDAAIDAAA"
if(message.matches("(A|D|I)")){
System.out.println("Matches");
}
You can use include all characters you are interested in within a square bracket. To match one or more occurrences of these characters in square brackets, append + to it. The message string should be entirely made up of only these characters for it to be considered a match.
Try this.
String message = "ADAIAIAIAIAIADDDAI";
if(message .matches("[ADI]+")) {
System.out.println("Matches");
}
Since you're asking about "words", I guess A, D and I stand for words with more than one letter and that that is the reaason why you're not using the character class [ADI]. You just have to add a + because the message consists of more words.
String message = "AIDDDAAIDAAA";
if (message.matches("(A|D|I)+")) {
System.out.println("Matches");
}
scigs answer works as well.
You could use string replace to do something similar:
String message = "AIDDDAAIDAAA";
message = message.replace("A","")
.replace("I","")
.replace("D","");
if (message.equals("")) {
//do your thing
}
You could just check each char composing the String:
String message = "AIDDDAAIDAAA";
boolean matches = true;
for (int i=0; i<message.length(); i++;){
if (message.charAt(i)!='A' && message.charAt(i)!='I' && message.charAt(i)!='D'){
matches = false;
break;
}
}
if (matches) System.out.println("Matches");
I am trying to set requirements for a certain number that a user requiers to enter(pNumber). pNumber should consist of 2 letters then 6 letters or numbers and finally a number.
I have implemented a method i found here on stackoverflow, but when i enter a number like: "LL^&%JJk9" it still gives me a positive result?
to my understanding .matches checks that a string only consists of the given values?
String First = pNumber.substring(0, 2);
String Middle = pNumber.substring(2, 8);
String Last = pNumber.substring(8, 9);
if (First.matches(".*[a-zA-Z].*") && Middle.matches(".*[a-zA-Z0-9].*") && Last.matches(".*[0-9].*")) {
greenOk.setVisibility(View.VISIBLE);
nextBtn.setEnabled(true);
} else {
redCross.setVisibility(View.VISIBLE);
}
You could use Apache Commons Lang for that. There you have methods like isNumeric and isAlphanumeric
Or use methods like Character isDigit
Maybe something like:
String input1 = "TYe4r5t12";
String input2 = "LL^&%JJk9";
String pattern = "([a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]{1})";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input1);
if (m.find()) {
System.out.println("Valid !!!");
}else{
System.out.println("Invalid !!!");
}
TextUtils class has various methods and one of them is given below.
TextUtils.isDigitsOnly(string)
This Stackoverflow details how to use Apache Commons to solve your problem.
If you are looking for a Regular Expression route of solving your issue, this will likely help you:
if(pNumber.matches("[a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]")) {
greenOk.setVisibility(View.VISIBLE);
nextBtn.setEnabled(true);
} else {
redCross.setVisibility(View.VISIBLE);
}
I have the following method which is used to insert parentheses and asterisks into a boolean expression when dealing with multiplication. For instance, an input of A+B+AB will give A+B+(A*B).
However, I also need to take into account the primes (apostrophes). The following are some examples of input/output:
A'B'+CD should give (A'*B')+(C*D)
A'B'C'D' should give (A'*B'*C'*D')
(A+B)'+(C'D') should give (A+B)'+(C'*D')
I have tried the following code but seems to have errors. Any thoughts?
public static String modify(String expression)
{
String temp = expression;
StringBuilder validated = new StringBuilder();
boolean inBrackets=false;
for(int idx=0; idx<temp.length()-1; idx++)
{
//no prime
if((Character.isLetter(temp.charAt(idx))) && (Character.isLetter(temp.charAt(idx+1))))
{
if(!inBrackets)
{
inBrackets = true;
validated.append("(");
}
validated.append(temp.substring(idx,idx+1));
validated.append("*");
}
//first prime
else if((Character.isLetter(temp.charAt(idx))) && (temp.charAt(idx+1)=='\'') && (Character.isLetter(temp.charAt(idx+2))))
{
if(!inBrackets)
{
inBrackets = true;
validated.append("(");
}
validated.append(temp.substring(idx,idx+2));
validated.append("*");
idx++;
}
//second prime
else if((Character.isLetter(temp.charAt(idx))) && (temp.charAt(idx+2)=='\'') && (Character.isLetter(temp.charAt(idx+1))))
{
if(!inBrackets)
{
inBrackets = true;
validated.append("(");
}
validated.append(temp.substring(idx,idx+1));
validated.append("*");
idx++;
}
else
{
validated.append(temp.substring(idx,idx+1));
if(inBrackets)
{
validated.append(")");
inBrackets=false;
}
}
}
validated.append(temp.substring(temp.length()-1));
if(inBrackets)
{
validated.append(")");
inBrackets=false;
}
return validated.toString();
}
Your help will greatly be appreciated. Thank you in advance! :)
I would suggest you should start with positions of + character in your string. If they differ by 1, you dont do anything. If they differ by two then there are two possiblities: AB or A'. So you check for it. If they differ by more than 2, then just check for ' symbol and put required symbol.
You can do it in 2 passes using regular expressions:
StringBuilder input = new StringBuilder("A'B'+(CDE)+A'B");
Pattern pattern1 = Pattern.compile("[A-Z]'?(?=[A-Z]'?)");
Matcher matcher1 = pattern1.matcher(input);
while (matcher1.find()) {
input.insert(matcher1.end(), '*');
matcher1.region(matcher1.end() + 1, input.length());
}
Pattern pattern2 = Pattern.compile("([A-Z]'?[*])+[A-Z]'?");
Matcher matcher2 = pattern2.matcher(input);
while (matcher2.find()) {
int start = matcher2.start();
int end = matcher2.end();
if (start==0||input.charAt(start-1) != '(') {
input.insert(start, '(');
end++;
}
if (input.length() == end || input.charAt(end) != ')') {
input.insert(end, ')');
end++;
}
matcher2.region(end, input.length());
}
It works as follows: the regex [A-Z]'? will match a letter from A-Z (all the capital letters) and it can be followed by an optional apostrophe, so it conveniently takes care of whether there is an apostrophe or not for us. The regex [A-Z]'?(?=[A-Z]'?) then means "look for a capital letter followed by an option apostrophe and then look for (but don't match against) a capital letter followed by an option apostrophe. This wil be all the places after which you want to put an asterisk. We then create a Matcher and find all the characters that match it. then we insert the asterisk. Since we modified the string, we need to update the Matcher for it to function properly.
In the second pass, we use the regex ([A-Z]'?[*])+[A-Z]'? which will look for "a capital letter followed by an option apostrophe and then an asterisk at least one time and then a capital letter followed by an option apostrophe". this is where all the groups that parentheses need to go in lie. So we create a Matcher and find the matches. we then check to see if there is already a parentese there (making sure not to go out of bounds ). If not we add a one. We again need to update the Matcher since we inserted characters. once this is over we have or final string.
for more on regex:
Pattern documentation
Regex tutorial
I want to check the last character of the String for characters that are not a non-word character using '\W' and allow certain symbols like ". , ! etc" from the top of my head I thought of using a code similar to this.
Boolean notCompleted = true;
int deduct = 1;
while(notCompleted){
if(string.charAt(string.length() -deduct) == '\W'){ // '\W' <-- doesn't work since it accepts anything other than "escape sequences".
if(string.charAt(string.length() -deduct) == '.'||string.charAt(string.length() -deduct) == ','||string.charAt(string.length() -deduct) == '!'){
//Do nothing and move on to the while loop
}else{
//Replace the non word character with ' '.
}
}
deduct++;
if(deduct >= html.length()){
notCompleted = false;
}
}
The reason why this doesn't work is because using string.charAt only accepts "Escapes sequence".
My question is there another way to pull this off rather than doing.
string.replaceAll("\W", "");
All suggestions is greatly appreciated. Thank you.
Thanks to the tip npinti gave me I built this code. However I am getting an error line
Desired Result of fakeNewString as requested should be "! asdsdefwef.,a,,sda.sd";
fakeNewString = sb.toString(); // NullPointerException
public static void test5(){
Boolean notCompleted = true;
String fakeNewString = "!##$%^&*( asdsdefwef.,a,,sda.sd";
int start = 0, end = 1;
StringBuilder sb = null;
try{
while(notCompleted){
start++;
String tempString = fakeNewString.substring(start, end);
if(Pattern.matches("\\W$", tempString)){
if(Pattern.matches("!", tempString)||Pattern.matches(".", tempString)||Pattern.matches(",", tempString)||Pattern.matches("\"", tempString)){
//do nothing
sb.append(tempString);
}else{
//Change it to spaces.
tempString = " ";
sb.append(tempString);
}
}
end++;
if(end >= fakeNewString.length()){
notCompleted = false;
fakeNewString = sb.toString();
System.out.println(fakeNewString);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
You can do something like so:
Pattern pattern = Pattern.compile("\\W$");
Matcher matcher = pattern.match(string);
if (matcher.find())
{
//do something when the string ends with a non word character
}
Take a look at this tutorial for more information on regular expressions.
You can use String.replaceAll in a slightly different way to do this. It achieves the same effect as the code you're trying to write, which seems like a complex solution for a simple problem. Try this code:
string.replaceAll("[^\\w!,.]", " ");
All the invalid characters are now replaced by a space, and multiple sequential occurrences of them are replaced by multiple spaces.
Lets try to break down the question (desire) and answer it:
I want to check the last character of the String for characters that are not a non-word character using '\W' and allow certain symbols like ". , ! etc"
First we have:
I want to check the last character of the String
Expression for character X at end of string:
X$
Then:
for characters that are not a non-word character
Expression:
[^\W] i.e. \w
And also:
allow certain symbols like ". , ! etc"
Added to the expression above:
[\w.,!]
And the combined final result is:
[\w.,!]$
Ta-da! (Altho I'm guessing OP is looking for something else, I did it for teh lulz.)
In Java is there a way to find out if first character of a string is a number?
One way is
string.startsWith("1")
and do the above all the way till 9, but that seems very inefficient.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
IN KOTLIN :
Suppose that you have a String like this :
private val phoneNumber="9121111111"
At first you should get the first one :
val firstChar=phoneNumber.slice(0..0)
At second you can check the first char that return a Boolean :
firstChar.isInt() // or isFloat()
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
I just came across this question and thought on contributing with a solution that does not use regex.
In my case I use a helper method:
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
#SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
Probably an overkill, but I try to avoid regex whenever I can.
To verify only first letter is number or character --
For number
Character.isDigit(str.charAt(0)) --return true
For character
Character.isLetter(str.charAt(0)) --return true