Using regex to validate a field - java

Sorry for being new to programming. Apparently I'm expected to know everything about the topic before posting here. I've only been doing this 3 weeks, learning as I go.
I've got a field limited to 5 characters I'm trying to validate. The first character must be a letter, and the following 4 characters must be numbers. Regex is like Greek to me at this point, so I'm having trouble. I've been able to get the first character validated, but I'm stumped on the remaining 4. Here's my code:
if (carID.substring(0, 1).matches("[0-9]")) {
showDataFormatError();
break;
} else {
if (carID.substring(1, 5).matches("[a-zA-Z]")) {
showDataFormatError();
break;
}
}
Updating to demonstrate my horrible coding at this point.
if (carID.length() < 5) {
showDataLengthError();
break;
} else {
if (carID.matches("^[a-zA-Z][0-9]{4}$")) {
showDataFormatError();
break;
} else {
if (carYearString.length() < 0) {
showDateLengthError();
break;
} else {
try {
int carYear = Integer.parseInt(carYearString);
int currentYear = Calendar.getInstance().get(
Calendar.YEAR);
// etc.

Try this
boolean valid = carID.matches("^[a-zA-Z][0-9]{4}$");
And see the tutorial
EDIT thanks to the down voter I spotted and fixed the error.

If you want to make sure the entire string is that format, use:
^[a-zA-Z]\d{4}$
this will help you and for tutorial you should have to go through this link
Regular Expression

I would do something like..
\pL Matches Any kind of letter from any language.
\pN{4} Matches Any kind of numeric character in any script. (4 times) greedy.
...
if (carID.length() > 5) throw IllegalArgumentException();
if (carID.matches("^\pL\pN{4}$")){
return true;
} else {
return false;
...
}

Related

How to validate phone number

I am trying to validate phone numbers in java. In my country, phone numbers either begin with 9 or 8 and only have 8 numbers. I have done
try {
Integer.parseInt(phoneNo);
}
catch (NumberFormatException e) {
msg += "Plese enter amount in Integers.\n";
}
if (phoneNo.length() == 0)
msg += "Please Enter Phone Number.\n";
if (phoneNo.length() != 8)
msg += "Invalid Phone Number.\n";
However I need to validate when the first digit of the number isn't 9 or 8. I am not entirely sure of how I am supposed to do that. Please explain how your code works as I am a student and I am trying to learn.
Just in case you are looking for a regular expression solution.
You can do use the following pattern ^(?=(?:[8-9]){1})(?=[0-9]{8}).* to perform the check.
Essentially what it does is;
From first character position ^
Look ahead and see if the first character is a 8 or 9 (?=(?:[8-9]){1})
Then see if there are a total of 8 digits (?=[0-9]{8})
If the above conditions is a match then mark this as matched .*
public static void main(String[] args) {
String telephoneNr = "88765432";
if (telephoneNr.matches("^(?=(?:[8-9]){1})(?=[0-9]{8}).*")) {
System.out.println("Valid phone number!");
}
else {
System.out.println("Invalid!");
}
}
Output:
Valid phone number!
The methods that you need to put this together are readily available on the String and Character classes.
Here is an example program that does what you are looking for:
public class Foo {
public static void main(String[] args) {
// First try null and the empty string
System.out.println(isValidPhoneNumber(null));
System.out.println(isValidPhoneNumber(""));
// Now try an otherwise valid string that doesn't have the right first character
System.out.println(isValidPhoneNumber("01234567"));
// Now try an invalid string
System.out.println(isValidPhoneNumber("9a934581"));
// Finally a valid number
System.out.println(isValidPhoneNumber("94934581"));
}
static boolean isValidPhoneNumber(String phoneNo) {
// First validate that the phone number is not null and has a length of 8
if (null == phoneNo || phoneNo.length() != 8) {
return false;
}
// Next check the first character of the string to make sure it's an 8 or 9
if (phoneNo.charAt(0) != '8' && phoneNo.charAt(0) != '9') {
return false;
}
// Now verify that each character of the string is a digit
for (char c : phoneNo.toCharArray()) {
if (!Character.isDigit(c)) {
// One of the characters is not a digit (e.g. 0-9)
return false;
}
}
// At this point you know it is valid
return true;
}
}
The output it produces is:
false
false
false
false
true
The final for-each loop could avoid re-checking the first character by using a for loop with an explicit counter, but the performance gain of not checking a single int doesn't outweigh the cleaner code and better readability of the for each construct.
Edit: also please note that I removed the validation error messages from the original question for better readability as the OP asked to explain what the code was doing.
Instead of taking the phone number in a Integer variable take it in a String variable.
Then check whether the 1st number is 9, 8 or not by using stringVariable.charAt(0)
and for length of the phone number use int len=stringVariable.length();
You can check the first character of the phoneNo:
if (phoneNo.charAt(0) != '9' && phoneNo.charAt(0) != '8') {
// the first character is not a 9 or an 8
}
Documentation for charAt from Oracle.

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string
I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.
I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:
public void isValidCode(String subjectCode2){
str = subjectCode2;
if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
System.out.println("The code is valid");
}
else {
System.out.println("The code is not valid");
}
You can always use Regular Expressions, and the matches() method of the String class.
if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
// Validation succeeded
}
else {
// Validation failed
}
To test that the first three letters are letters, you could use a loop. Similarly, use a loop for testing that the last three digits are numbers. You might find the functions in the Character class helpful.
I would change the method signature so that it is not a void method but rather declared to return a boolean. Then you could have several if statements that if false returns false. At the bottom, return true if it passes all tests.
public boolean isValidCode(String code) {
if (code.length() != 6) {
return false;
}
// here check if first 3 chars are letters
// here check if last 3 chars are numbers
return true;
}
Then the calling code can do a println if desired.
String test = "ABC123";
if (isValidCode(test)) {
System.out.println("The code is valid");
} else {
System.out.println("The code is not valid");
}
If by "letter", you mean to include letters in alphabets other than English, you'll need this.
if (str.matches("\\p{L}{3}\\d{3}")) {
Here, \p{L} matches any character that Unicode considers to be a letter, in any language.

How to convert this regular expression into a format java can use?

I want to use regular expressions to be able to parse a sequence like this...
ifelseifelseififif
Where every else needs an if but not every if needs an else. I plan on using this expression
((if)*+(ifelse)*)*
but I don't know how to convert that into the format that I can use in java. Could someone show me and break it down for me?
You probably want: ((if)*|(ifelse)*)*. The | means "or".
However, it's unclear what you hope to accomplish with this. Your input seems ambiguous. It could be
if {
} else {
}
if {
} else {
}
if {
}
if {
}
if{
}
or it might be
if {
} else {
if {
} else {
}
}
if {
}
if {
}
if {
}
or many other variations.
In regex logic we want to match:
(if if
| OR
ifelse) ifelse
* That token, 0 or more times.
(if|ifelse)*
This will match 0 or more if/elseifs.
If you need it to fill the entire string from start to end, e.g. no partial matches, put ^ before it and $ after it:
^(if|ifelse)*$
Please read http://www.regular-expressions.info/reference.html for an introduction to regex syntax (for instance, + is not what you think it is in regexes), and use http://www.regexpal.com to test your regexes quickly in the browser.

Equivalent of 'where' fortran keyword in Java?

I'm writing a Java program in which I'm checking a list against a string, and then doing stuff to that. In fortran I'd write something along the lines of
where(list(:)==stringToCheck){
...
statements
...
}
Instead I have a headache of a block of for-loops, if staments and breaks all over the place. No perhaps I could neaten the code a little but it still feels far more inefficient than fortran.
Edit, this is the code I've resorted to:
for(int idx=0;idx<player.get_charactersOwned().size();idx++)
{
if(player.get_charactersOwned().get(idx).get_characterName().equals(charName))
{
/* Add character to the game
* Add game to the character*/
System.out.println("Character "+charName+" Found ");
gameToMake.addCharacters(player.get_charactersOwned().get(idx));
player.get_charactersOwned().get(idx).addGame(gameToMake);
break;
}else
{
System.err.println("Character "+ charName +" not found");
System.out.println("Shall I add that Character? y/n ");
choice = scanner.nextLine();
if(choice.equalsIgnoreCase("y"))
{
charName = scanner.nextLine();
Character character = new Character(charName);
characterTempList.add(character);
player.addCharacter(characterTempList);
gameToMake.addCharacters(player.get_charactersOwned().get(idx));
player.get_charactersOwned().get(idx).addGame(gameToMake);
break;
}else{break;}
}
}
As tempting as it is to fix this code, I'd much rather use a work around.
Is there a Java equivilant of this without the use of external libraries?
No, there isn't an equivalent in Java. Instead if you need to check if a list of characters (each with a name) contains a character name then simply do this:
// search the name
boolean found = false;
for (Character c : player.get_charactersOwned()) {
if (c.get_characterName().equals(charName)) {
found = true;
break;
}
}
// perform the check
if (found) {
// do something
} else {
// do something else
}
And by the way, Character is a bad name for your class, it clashes with Java's own Character class. Rename it if possible, to avoid confusion. Alternatively, the loop could have been written like this:
boolean found = false;
for (int i = 0, n = player.get_charactersOwned().size(); i < n && !found; i++) {
Character c = player.get_charactersOwned().get(i);
if (c.get_characterName().equals(charName)) {
found = true;
}
}

Can I improve this Pig-Latin converter? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm brand-spanking new to Java and I made this little translator for PigLatin.
package stringmanipulation;
public class PigLatinConverter {
public String Convert(String word){
int position = 0;
if (!IsVowel(word.charAt(0))) {
for (int i= 0; i < word.length(); i++) {
if (IsVowel(word.charAt(i))) {
position = i;
break;
}
}
String first = word.substring(position, word.length());
String second = word.substring(0, position) + "ay";
return first + second;
} else {
return word + "way";
}
}
public boolean IsVowel(char c){
if (c == 'a')
return true;
else if(c == 'e')
return true;
else if(c == 'i')
return true;
else if(c == 'o')
return true;
else if(c == 'u')
return true;
else
return false;
}
}
Are there any improvements I can make?
Are there any nifty Java tricks that are in the newest Java version I might not be aware of? I come from a C# background.
Thank you!
I'd rewrite isVowel(char ch) as follows:
return "aeiou".indexOf(ch) != -1;
And I'd write the following instead:
// String first = word.substring(position, word.length());
String first = word.substring(position);
I'd also rename method names to follow coding convention.
And of course, being me, I'd also use regex instead of substring and for loop.
System.out.println("string".replaceAll("([^aeiou]+)(.*)", "$2$1ay"));
// ingstray
References
Java Coding Convention - Naming Convention
Disclaimer: I don't know Java.
Inverted logic is confusing please write your if statement as such:
if (IsVowel(word.charAt(0))) {
return word + "way";
} else {
for (int i= 0; i < word.length(); i++) {
// ...
return first + second;
}
You can even drop the else.
IsVowel may need to be private. It can also be rewritten using a single || chain, or as a "".indexOf (or whatever it is in Java).
Your for logic can be simplified int a short while:
while (position < word.length() && !IsVowel(word.charAt(position)) {
++position;
}
Here's a complete rewrite that makes the code more readable if you know how to read regex:
String[] words =
"nix scram stupid beast dough happy question another if".split(" ");
for (String word : words) {
System.out.printf("%s -> %s%n", word,
("w" + word).replaceAll(
"w(qu|[^aeiou]+|(?<=(w)))([a-z]*)",
"$3-$1$2ay"
)
);
}
This prints (as seen on ideone.com):
nix -> ix-nay
scram -> am-scray
stupid -> upid-stay
beast -> east-bay
dough -> ough-day
happy -> appy-hay
question -> estion-quay
another -> another-way
if -> if-way
Note that question becomes estion-quay, which is the correct translation according to Wikipedia article. In fact, the above words and translations are taken from the article.
The way the regex work is as follows:
First, all words are prefixed with w just in case it's needed
Then, skipping that w, look for either qu or a non-empty sequence of consonants. If neither can be found, then the actual word starts with a vowel, so grab the w using capturing lookbehind
Then just rearrange the components to get the translation
That is:
"skip" dummy w
|
w(qu|[^aeiou]+|(?<=(w)))([a-z]*) --> $3-$1$2ay
\ 2\_/ /\______/
\_________1_________/ 3
References
regular-expressions.info
Character class:[…], Alternation: |, Repetition:+,*, Lookaround:(?<=…), and Capturing:(…)
I know this question is well over a year old, but I thought I would put my modification of it. There are several improvements in this code.
public String convert(String word)
{
int position = 0;
while(!isVowel(word.charAt(position)))
{
++position;
}
if(position == 0)
{
return word + "-way";
}
else if(word.charAt(0) == 'q')
{
++position;
}
return word.substring(position) + "-" + word.substring(0, position) + "ay";
}
public boolean isVowel(char character)
{
switch(character)
{
case 'a': case 'e': case 'i': case 'o': case 'u':
return true;
default:
return false;
}
}
First the code will find the position of the first vowel, and then jump out of the loop. This is simpler than using a for loop to iterate through each letter and using break; to jump out of the loop. Secondly, this will match all the testcases on the Wikipedia site. Lastly, since chars are actually a limited range int, a switch statement can be used to improve performance and readability.
Not strictly an improvement as such, but Java convention dictates that methods should start with a lowercase letter.
I'm years removed from Java, but overall, your code looks fine. If you wanted to be nitpicky, here are some comments:
Add comments. It doesn't have to follow the Javadoc specification, but at least explicitly describe the accepted argument and the expected return value and perhaps give some hint as to how it works (behaving differently depending on whether the first character is a vowel)
You might want to catch IndexOutOfBoundsException, which I think might happen if you pass it a zero length string.
Method names should be lower case.
IsVowel can be rewritten return c == 'a' || c == 'e' and so on. Due to short-circuiting, the performance in terms of number of comparisons should be similar.
Is this homework? If so, tag it as such.
Unclear what expected behaviour is for "honest" or "ytterbium".
It doesn't respect capitals ("Foo" should turn into "Oofay", and AEIOU are also vowels).
It crashes if you pass in the empty string.

Categories

Resources