Input, via a question, the report owner’s first name as a string.
Need a regular expression to check, conditionally, to make sure the first name doesn’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The first name can not contain any white space either.
do
{
System.out.println("Please enter your FIRST name:");
firstName = keyboard.next();
firstName= firstName.toUpperCase();
}
while( !firstName.matches("^/s^[a-zA-Z]+$/s"));
System.out.println("Thanks " + firstName);
Output
p
Please enter your FIRST name:
p p
Please enter your FIRST name:
Please enter your FIRST name:
You've got your regex muddled up. Try this:
while(!firstName.matches("^[^\\d\\s]+$"));
The regex "^[^\\d\\s]+$" means "non digits or whitespace, and at least one character"
If you want to eliminate digits, just force:
\D*
In your matcher
As you have firstname in uppercase and matches method matches the whole input,
[A-Z]+ is sufficient.
while( !firstName.matches("[A-Z]+"));
or
while( !firstName.matches("\\p{Lu}+"));
Try this one: ^[a-zA-Z,.'-]+$. :D
Also, if you want to try out your regular expressions, rubular.com is a great place for that :D
You used Scanner#next, instead of Scanner#nextLine.
From Scanner#next JavaDoc:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
I believe one such delimiter is \s+ :D
import java.util.Scanner;
public class FirstNameParser {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String firstName = null;
do {
System.out.print("Please enter your FIRST name: ");
firstName = keyboard.nextLine();
firstName = firstName.toUpperCase();
}
while (!firstName.matches("^[a-zA-Z,.'-]+$"));
System.out.println("Thanks " + firstName);
}
}
Try
firstName = firstName.replaceAll("[\\d\\s]", "").toUpperCase();
You can try this. Created it using Rubular.com. The
Pattern nameRequirment = Pattern.compile("^((?!.[\\d\\s]).)*$");
while (!nameRequirement.matcher(myString).matches()){
//... prompt for new name
}
Related
I am writing a code that takes a person's name and sees if it fits the REGEX criteria. If it does, it follows through a loop and continues on with the code. If the name is not valid, the code will exit. So far I have made it so it can take input and check the names. It is working for all except 2 names. O’Malley, John F. and John O’Malley-Smith. These two names need to be acceptable but the code keeps kicking them out saying they are invalid.
So far I have attempted using
String REGEX = ("^[\\-\\.\\'\\, a-zA-Z ]*$");
This gets me a solid return on all the names except for the 2 mentioned above. I know I have to add somethings to the REGEX code, and have attempted \b boundaries, however have had no luck getting them to work. Any help would be appreciated on what I should add to the REGEX and where to put it inside the code. Here is also the list of valid and invalid names, as well as my code.
Acceptable inputs for name:
Bruce Schneier
Schneier, Bruce
Schneier, Bruce Wayne
O’Malley, John F.
John O’Malley-Smith
Cher
Unacceptable inputs for name:
Ron O’’Henry
Ron O’Henry-Smith-Barnes
L33t Hacker
//alert(“XSS”)//
select * from users;
(All Invalid Names Are Not Accepted At This Time)
public class InputAsker {
public static void main (String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please Input Your Name: ");
String myName = keyboard.nextLine();
String REGEX = ("^[\\-\\.\\'\\, a-zA-Z ]*$");
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(myName);
boolean matchfound = false;
while (matcher.find()) {
System.out.println("That's A Great Name! Let's Continue");
matchfound = true;
//loop will continue here
}
if (!matchfound) {
System.out.println("Sorry, Not A Valid Name! Please Try Again!");
}
}
}
Enter two words: computer program
result: cute
the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute"
thought of using replaceAll but could not make it work.
String sentence;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 words: ");
sentence = input.nextLine();
String[] arrWrd = sentence.split(" ");
String scdWrd = arrWrd[1];
String fnl = arrWrd[0].replaceAll(scdWrd, "");
System.out.println(fnl);
.replaceAll takes a regex, so basically what you are doing here is you're searching for the whole "program" word and replacing it and not its characters, so you just need to add brackets to your scdWrd to let it know that you want to replace the chars:
String scdWrd = "[" + arrWrd[1] + "]";
Just to add to the elegant solution by #B.Mik, you should also check for things like
If multiple spaces are entered between the words.
If the user enters a blank line or just one word e.g. execute your program and enter a blank line or just one word e.g. computer and you will be welcomed with java.lang.ArrayIndexOutOfBoundsException.
The program given below addresses these points:
import java.util.Scanner;
public class LettersFromSecondReplacement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid;
String input;
String words[];
do {
valid = true;
System.out.print("Enter two words separated with space: ");
input = in.nextLine();
words = input.split("\\s+"); //Split on one or more spaces
if (words.length != 2) {
System.out.println("Error: wrong input. Try again");
valid = false;
}
} while (!valid);
for (String s : words[1].split("")) { //Split the 2nd word into strings of one character
words[0] = words[0].replaceAll(s, "");
}
System.out.println(words[0]);
}
}
A sample run:
Enter two words separated with space:
Error: wrong input. Try again
Enter two words separated with space: computer
Error: wrong input. Try again
Enter two words separated with space: computer program
cute
Note that I have used a different algorithm (which you can replace with the one provided by #B.Mik) for replacement. Feel free to comment in case of any doubt/issue
replace line with replaceAll by
String fnl = arrWrd[0];
for (byte c : scdWrd.getBytes()) {
fnl = fnl.replace("" + (char)c, "");
}
If I have a string with numbers and characters and I want to replace the numbers with a certain character, I can use replace with a regualr expression. However it replaces EVERY number with that character. What would be the best way to change this behavior?
import java.util.Scanner;
public class Regexp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Enter you name");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceFirst("[^A-Za-z]", ":");
System.out.println(firstname1);
// TODO code application logic here
}
}
See the above code. If I were to enter in jsahdk1283, it would return jsahdk::::, when I just want jsahdk:. Is this possible?
Thanks,
Ben
As RC and TheLostMind mentioned in the comments, you should use a quantifier like this:
firstname1 = firstname1.replaceFirst("[^A-Za-z]+", ":");
Here, the + coming after the character class means "one or more".
Note that [^A-Za-z] will match ANYTHING that is not an English letter, such as accented characters and punctuation. It's therefore a better idea to use \d.
firstname1 = firstname1.replaceFirst("\\d+", ":");
I have a scenario where user has to enter its first Name and last name in a single field, so there must be a space between 2 names, and after space there must be atleast a character. I tried to using contains(""), but this method returns true if user just enter a space and does not enter anything after that space.
Kindly guide me a way to achieve this. I have also tried to search Regular Expression but failed to find any.
Here is the regex and a test:
#Test
public void test_firstAndLastName_success() {
Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)");
Matcher matcher = ptrn.matcher("FirstName LastName");
if (matcher.find()) {
Assert.assertEquals("FirstName", matcher.group(1));
Assert.assertEquals("LastName", matcher.group(2));
} else {
Assert.fail();
}
}
The validation is the matcher returning false on find.
If you do not want to permit multiple spaces (\s+) then either remove + (which will still permit for a single tab) or replace it with a space.
You can use code like this:
public static void main(String[] args) throws IOException {
String input = "first last";
if (input.matches("[a-zA-Z]*[\\s]{1}[a-zA-Z].*")) {
String[] name = input.split(" ");
System.out.println(Arrays.toString(name));
} else {
System.out.println("Please input the valid name.");
}
}
It will put first name and last name to array if:
[a-zA-Z]* - input begins with characters;
[\\s]{1} - contains only one space;
[a-zA-Z].* - ends with at least one character.
A simple split using " " will do after trimming the string.
Please check the below code for more understanding :
String[] splitter = null;
String s = "abbsd sdsdf"; // string with 2 words and space
splitter = s.trim().split(" ");
if(splitter.length!=2){
System.out.println("Please enter first or last name");
}
else{
System.out.println("First Name : "+splitter[0]);
System.out.println("Last Name : "+splitter[1]);
}
s = "abc"; //string without space
splitter = s.trim().split(" ");
if(splitter.length!=2){
System.out.println("Please enter first or last name");
}
else{
System.out.println("First Name : "+splitter[0]);
System.out.println("Last Name : "+splitter[1]);
}
Please check with other scenarios with and without space. This should be helpful.
String getname(){
Scanner input = new Scanner(System.in);
String name;
System.out.println("Enter your name:");
name= input.next();
String name_pattern = "^[A-Za-z]+(\\s[A-Za-z]+)$";//this regex isnt validating Ben Smith
Pattern pattern = Pattern.compile(name_pattern);
Matcher regexmatcher = pattern.matcher(name);
if(!regexmatcher.matches()){
System.out.println("Name format not correct");
}
return name;
}
I also need to take the input again and again until the correct format is entered. How do i do that? My current regex prints "Name format not correct" when I input "Ben Smith" though it should not print that because Ben Smith is a valid input!
input.next returns the next token from the input rather than the next line. You may set another delimiter in Scanner to return lines but the most custom way is to use
name= input.nextLine();
The Scanner's next() method returns only the next word, in your case "Ben". Replace that with nextLine() to get the whole name.
Scanner input = new Scanner(System.in);
String name;
System.out.println("Enter your name:");
name = input.nextLine();
With that your regular expression matches "Ben Smith".
^[A-Za-z ]+$ is enough.
private final static Pattern NAME_VALIDATOR = Pattern.compile("^[A-Za-z ]+$");
[...]
System.out.println(NAME_VALIDATOR.matcher("Ben Smith").matches());
Note that the Pattern is always the same, so you can just create it once instead of creating it every time you enter the method.
Also note that this will not validate names with ', e.g. O'Brian, neither foreign names, e.g. Mätthaus. Consider using \p{L} instead.
As a comment points out:
"As far as I understand they want only two words with a space
inbetween to be valid"
Then the regex would be "^[A-Za-z]+ [A-Za-z]+$" instead.