How would I do java regex for the following examples each its taken in by scanner as a string and regex can only be set after the scanner has taken in each part so where regex can be set is after the scanner e.g
Scanner scan = new Scanner(System.in);
String veriableName = scan.nextLine();
String studentID = scan.nextLine();
String word = scan.nextLine();
................
//regex can only be set here
String veriableNamePattern = "";
String studentIDPattern="";
String wordPattern="";
.............
if(veriableNamePattern.matches(veriableNamePattern ){
System.out.println(veriableName + " is valid.");
}
else{
System.out.println(studentID + " is valid.");
}
here are the examples I am trying to do:
A variable name composed of some alphabetic character followed by any sequence of letters or numbers.
A student ID number represented by 7 digits that must start with 1 and end with the letter s.
Any four letter word that ends in ‘ed’.
A product code represented by two digits followed by three capital letters.
Find all € values from €100 to €999 at the beginning of a line.
Just.. read through your code, treat it like a term paper, you proofread those too, surely:
You are calling veriableNamePattern.matches(veriableNamePattern) - it won't, of course. You want to match veriableName.
You print studentID + " is valid." in both cases, making it impossible to tell the difference. presumably you want to introduce a not somewhere in that second println lline.
Some examples:
// first letter optionally followed by a letter/number/underscore (\w) group
String variablePattern = "[a-zA-Z]\\w*";
// Sequence of digits starting with 1, followed by 6 digits, ending with 's' or 'S'
String studentIdPattern = "1[0-9]{6,6}s|S";
// Sequence of 2 letters followed by "ed"
String fourEdPattern = "[a-zA-Z]{2,2}ed";
Related
I'm trying to do a simple validation for vehicle registration number.
It must include "-" Dash/Hyphen symbol. Example: BIR - 5698
It allows Numbers/Letters and Hyphen symbol only.
All the other symbols are invalid. ( `~!##$%^&*()_+=./;,<>":|[]{} )
My code -
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if (in.hasNext("[A-Za]")) {
System.out.println("Vehicles :" + vehicles );
}else {
System.out.println("Enter a Valid Value");
Thank you. Your kind help highly appreciated.
I'm not sure if what you show as an example registration number is the actual format for a vehicle registration number (3 chars, a dash, 4 chars). Does the whitespace before and after the dash need to be there or is that optional? Are there only three alphanumeric characters before the dash and always 4 alphanumeric character after the dash? Because you haven't indicated as such either way I'm going to assume so. The supplied Regular Expression below can be easily modified to accommodate whatever format(s) are required.
Here is the code:
String ls = System.lineSeparator();
Scanner in = new Scanner(System.in);
String vrn = "";
while (vrn.isEmpty()) {
System.out.print("Please enter a valid Vehicle Registration number" + ls
+ "or 'q' to quit: -> ");
vrn = in.nextLine().trim();
if (vrn.equalsIgnoreCase("Q")) { //Quit?
return;
}
// Validate entry...
if (!vrn.matches("(?i)[A-Z0-9]{3} ?\\- ?[A-Z0-9]{4}")) {
System.out.println("Invalid Vehicle Registation Number! ("
+ vrn + ") Try again..." + ls);
vrn = ""; // Empty vrn so to re-loop.
}
}
System.out.println("VALID VRN!");
About the Regular Expression (regex):
(?i) Letter case insensitive;
[A-Z0-9]{3} Any 3 alphanumeric character (A to Z, a to z, or 0 to 9) before the dash;
? An optional single whitespace before the mandatory dash (-);
\\- A mandatory single literal Dash character;
? An optional single whitespace after the mandatory dash (-);
[A-Z0-9]{4} Any 4 alphanumeric characters (A to Z, a to z, or 0 to 9) after the dash;
If you want to change the number of allowable characters within the regex then you can consider any one of these few examples:
{3} Strictly 3 characters allowed only;
{3,6} Strictly 3 to 6 characters allowed only;
{3,} 3 or more characters allowed;
`{0,} 0 or more characters allowed.
Add all valid characters:
if (in.hasNext("[A-Za-z0-9\-]")) {
So I'm supposed to use the scanner to read the users employee number and then put that into a method that returns a boolean value. The employee is supposed to have the form DDDDD-LDDDD with the d being digits and l being letters. If the input matches this format I'm supposed to inform the user that they have a valid number and if it doesn't then I have to say it's invalid. I've trying to separate into two substrings to be able to see if they contain digits as well as to see if it contains a letter. I then try to combine these using a loop and if it's in that format the user is told it's valid and if it's not they are informed it's not. Is there any other possible way to check and see if the employee number is composed of digits besides obviously the dash and letter that I can then use to prompt the user if what they wrote is valid? This is only written in Java
You can use regular expressions:
final String[] strings = {
"54321-A1234", // A valid employee ID
"012948B9832", // The dash is replaced with a number
"39832-30423", // The letter is replaced with a number
"24155-C90320", // A valid employee ID but the last number
};
for (String string : strings) {
if (string.matches("[0-9]{5}-[A-Za-z]{1}[0-9]{4}")) {
System.out.println("The string " + string + " is a valid pattern.");
} else {
System.out.println("The string " + string + " is an invalid pattern.");
}
}
This will output
The string 54321-A1234 is a valid pattern.
The string 012948B9832 is an invalid pattern.
The string 39832-30423 is an invalid pattern.
The string 24155-C90320 is an invalid pattern.
Explanation:
[0-9]{5} means "match exactly five digits";
- means "match the character - exactly one time";
[A-Za-z]{1} means "match exactly one letter, case-insensitive";
[0-9]{4} means "match exactly four digits";
Note that [0-9] can be replaced with \\d and that {1} is optional, but I've added just for explicitness.
You can do it with a regular expression. This prompts for the string and if not in proper format, reprompts.
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("Please enter string in DDDDD-LDDDD format");
while (true) {
str = input.nextLine();
// checks for 5 digits followed by - one letter and four digits.
if(str.matches("\\d{5}-\\p{Alpha}\\d{4}")) {
break;
}
System.out.println("Please try again!");
}
System.out.println(str + " is a valid string");
When I input any sentence, my output returns that any string is a palindrome, and I think that my replaceAll calls aren't working in some cases. This is likely due to error my part, because using the Scanner class in Java is new for me (more used to input from C++ and Python3). I added comments to make it clearer what my intentions were when writing the program.
import java.util.Scanner;
public class PalindromeTest
{
public static void main (String[] args)
{
Scanner stringScan = new Scanner(System.in); //Scanner for strings, avoids reading ints as strings
Scanner intScan = new Scanner(System.in); //Scanner for ints, avoids reading strings as ints
String forwardPal = ""; //Variables for the rest of the program
String reversePal = "";
String trimForward = "";
char tempChar;
int revCount;
int revPalLength;
int quit;
while (true) //Loop to keep the program running, problem is in here
{
System.out.println("Please enter a word or a sentence."); //Prompts user to enter a word or sentence, I assume that the program is counting
forwardPal = stringScan.nextLine();
trimForward = forwardPal.replaceAll(" " , ""); //Trims the forwardPal string of characters that are not letters
trimForward = trimForward.replaceAll("," , "");
trimForward = trimForward.replaceAll("." , "");
trimForward = trimForward.replaceAll("!", "");
trimForward = trimForward.replaceAll(":", "");
trimForward = trimForward.replaceAll(";", "");
revPalLength = trimForward.length() ; //Makes the reverse palindrome length equal to the length of the new trimmed string entered
for (revCount = revPalLength - 1; revCount >= 0; revCount--) //Loop to count the reverse palindrome and add each character to the string reversePal iteratively
{
tempChar = trimForward.charAt(revCount);
reversePal += tempChar;
System.out.println(reversePal);
}
if (trimForward.equalsIgnoreCase(reversePal)) //Makes sure that the palindrome forward is the same as the palindrome backwards
{
System.out.println("Congrats, you have a palindrome"); //Output if the sentence is a palindrome
}
else
{
System.out.println("Sorry, that's not a palindrome"); //Output if the sentence isn't a palindrome
}
System.out.println("Press -1 to quit, any other number to enter another sentence."); //Loops to ask if the user wants to continue
quit = intScan.nextInt(); //Checks if the user input a number
if (quit == -1) //If the user inputs -1, quit the program and close the strings
{
stringScan.close();
intScan.close();
break;
}
}
}
}
Your problem is this line
trimForward = trimForward.replaceAll("." , "");
That function takes the first argument as a regex, and the dot means that it is replacing all characters as a "".
Instead, use
trimForward = trimForward.replace("." , "");
In fact, all your lines should be using #replace instead of #replaceAll as none of them take advantage of regex. Only use those if you plan to take advantage of it.
Or in fact, if you do want to use a regex, this is a nice one which does all of that in one neat line.
trimForward = forwardPal.replaceAll("[ .!;:]" , "");
I hope this was of some help.
The simplest fix is to use replace() instead of replaceAll().
replace() replaces all occurences of the given plain text.
replaceAll() replaces all occurences of the given regex.
Since some of your replacements have special meaning in regex (specifically the dot ., which means any character), you cant use replaceAll() as you are currently (you'd have to escape the dot).
It's common, and quite reasonable, to assume that replace() replaces one occurrence and replaceAll() replaces all occurrences. They are poorly named methods, because they interpret their parameters differently, yet both replace all matches.
As an aside, you may find this briefer solution of interest:
forwardPal = forwardPal.replaceAll("\\W", ""); // remove non-word chars
boolean isPalindrome = new StringBuilder(forwardPal).reverse().toString().equals(forwardPal);
I have this program to write and have no idea how to control keyboard input:
Write a method to check whether the word entered is valid or not.
Valid word should:
Have at least 10 characters
Start with a letter
Contain a letter in upper case
Contain at least 3 digits
Contain a special character (e.g. #,$.% …etc)
Contain a space
You don't need to validate it on every key stroke, wait till the user has entered the word, then validate. Assuming you are using console input:
System.out.print("Enter something > ");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
//perform validations on inputString, heres the first one:
//regex could be used instead of multiple if statements
if(inputString.length() < 10) {
System.out.println("Validation failed, word was too short");
}
else if ...
You can use this regular expression:
String REGEX = "(^[a-zA-Z](?=.*\\d{3,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%])(?=\\s+).{10,})";
String INPUT = "your password";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(INPUT);
System.out.println("matches(): "+matcher.matches());
^[a-zA-Z] # Start with a letter
(?=.*\\d{3,}) # at least three digits must occur
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[##$%]) # a special character must occur at least once
(?=\\s+) # a space must occur at least once
.{10,} # anything, at least ten places though
$ # end-of-string
To use this, read your password (from file,swing elements,...) and call a method, say validate(String pass), inside validate check it against the regex.
Scanner input=new Scanner(System.in);
System.out.print("Enter Number");
//in here "input" is a Scanner name you can use any name for it as OBAMA.
int x=input.nextInt();
//here you can assigne the key board value for "x".
System.out.println(x);
then you can print it.
I'm having problems with the code below. It asks for the user to type in a sentence basically.
System.out.println("Enter a string containing spaces: ");
inputString = keyboard.next();
int lengthString = inputString.length();
System.out.println("You entered: " + inputString + "\n" + "The string length is: " + lengthString);
The problem is when it prints the statement, it only prints the first word, then counts the characters contained within the first word. I'm really new to Java, so I was wondering what should I do to make the program count the WHOLE string.
You should use nextLine() method instead of next():
inputString = keyboard.nextLine();
Scanner#next() method reads the next token. Tokens are considered to be separated by a delimiter. And the default delimiter of Scanner is as recognized by Character.isWhitespace.
keyboard.nextLine() will pull in the entire line. next() only gets the next word. next() uses spaces by default to determine word sizes, but you can also set a custom delimiter if you want it to pull in different tokens.