Java if else on partial match - java

I've moved into Selenium WebDriver, and still finding the most confusing examples.
I need to be able to read a string (succeeded) run a conditional that asks If specific text is present.
For the sake of this text.
String oneoff = "Jeff is old"
I need to match on Jeff, see code below, as long as Jeff exists in the string, I want to return true. If Jeff doesn't exist, then I will check for oh say 50-75 other names. However the string may contain their name and additional text that cannot be controlled. so I have to do a partial match.
Question 1. am I screwed and will have to build each regex expression in that crazy format that I have been seeing, or am I missing something obvious?
Question 2. Will someone for my sanity please show me the proper way to match on Jeff, with the possibility of text being before and after the name Jeff.
Thank you!
String oneoff = driver.findElement(By.id("id_one_off_byline"))
.getAttribute("value");
System.out.println("One Off is:" + oneoff);
if (oneoff.matches("Jeff")) {
System.out.println("It is Jeff");
} else {
System.out.println("it is not jeff");
}
This is just the functional part of the code,

as Jeff exists in the string, I want to return true
Then you probably should test it with
if (oneoff.contains("Jeff"))
since matches use regex as parameter, so if (oneoff.matches("Jeff")) would return true only if oneoff = "Jeff".

You do not need to use match() for the code you have supplied. Instead use oneoff.equals("String") for string matching. Match() is more for a regex expressions. You could also use oneoff.contains("String") if you want to return true even if the string only exists as a subset of the target string.

if (oneoff.contains("Jeff")) {
System.out.println("It is Jeff");
} else if (!oneoff.contains("Jeff")) {
System.out.println("it is not jeff");
}
I think you should improve your code to be like this, because java probably didn't recognize else string if contained with other "jeff" maybe "JEef" or "JEEF" or even maybe "Jeef "
I hope it works, I used to found same bug like yours and I try this way to overcome it.

Related

How to check the return value of the method with the value of the string?

I have to check the return value of the method, if it equals the value of a string which is either "Yes" or "No" or should I use a regex which matches with the pattern of the string i.e Yes or No.
So essentialy, I am trying to write in this way
if ((ru.getTest()).equals(("Yes") || (“No”)))
{......
Is it the way , I should proceed or am wrong?
Adding to it.
I would like to post a detailed explanation of my question.
if(ru.getTest().equals("yes/oui") || ru.getTest().equals("no/non")),
It is not just Yes but along with the French literal added to it. So, if (the above condition is met), it should trim the French literal portion and keep only the 'yes' or 'no'..
I tried with this:
if ((ru.getTest()).equals("Yes/Oui") || (ru.getTest()).equals(“No/Non”)) {
Test = ru.getTest().substring(0, Test.indexOf ('/'));
Please correct me If I am wrong.
You can basically just write:
if(ru.getTest().equals("yes") || ru.getTest().equals("no"))
I believe a simple check can be done by using equals and not necessarily using regex. Regex tends to be used for more complex matching scenarios.
Use matches() for regex:
if (ru.getTest().matches("(?i)yes|no"))
If you just want to trim the part after and including a possible slash, you don't even need to check anything first:
String trimmed = ru.getTest().replaceAll("/.*", "");
This will work whether or not there is a slash.
You can write like this.
String s = ru.getTest().toLowerCase();
if(s.contains("yes") || s.contsins("oui")) {
Test = "yes";
} else {
Test = "no";
}
If there are different input, use s.matchs() method for regular expression

String.contains always appears false

public final void nameErrorLoop () {
while (error) {
System.out.println("Enter the employee's name.");
setName(kb.next());
if (name.contains("[A-Za-z]")) {
error = false;
}
else {
System.out.println("The name can only contain letters.");
}
}
error = true;
}
Despite a similar setup working in a different method, this method becomes stuck in a constant loop because the if statement is always false. I've tried .matches(), and nothing that I found on the Interent has helped so far. Any ideas why? Thanks for your help in advance.
Edit: I just noticed as I was finishing the project, that trying to print 'name' later only shows the first name, and the last is never printed. Is there any way I can get the 'name' string to include both?
String.contains doesn't use regular expressions - it just checks whether one string contains another, in the way that "foobar" contains "oob".
It sounds like you want to check that name only contains letters, in which case you should be checking something like:
if (name.matches("^[A-Za-z]+$"))
The + (instead of *) will check that it's non-empty; the ^ and $ will check that there's nothing other than the letters.
If you expect it to be a full name, however, you may well want to allow spaces, hyphens and apostrophes:
if (name.matches("^[-' A-Za-z]+$"))
Also consider accented characters - and punctuation from other languages.
Easy. .contains() is not what you think. It does exact String matching.
"anything".contains("something that's not a regular expression");
Either use this
Pattern p2=Pattern.compile("[A-Za-z]+");//call only once
p2.matcher(txt).find();//call in loop
or this:
for(char ch: "something".toCharArray()){
if(Character.isAlphabetic(ch)){
}
}

How to validate file path?

Edit 1
I am stuck on a little problem and the guy who I normally turn to is, believe it or not, in Australia on his honeymoon, how inconsiderate is that.
The problem is that I have worked on trying to get a boolean which will either let me know if the file path is correct or not.
The problem is that it always returns false,
I have tried the following sample data
c:\Lingerie\
c:\\Lingerie\\
c:\\
c:\
Edit
This is the input screen that I have developed so far. I have already thought of having extra white spaces, so I already popped in the trim command.
They all have returned false.
Here is the method that I'm using and the code that calls it.
dbFilePath = (text.getText()).trim();
bool03 = busLog.isFilePath(dbFilePath);
System.out.println("The result is " + bool03);
And the method is called is
public boolean isFilePath(String filePath) {
return discreetLog.isFilePathMatched(filePath);
}
And which calls
public boolean isFilePathMatched(String myFilePath){
String regularExpression = "([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?";
Pattern pattern = Pattern.compile(regularExpression);
return Pattern.matches(regularExpression, myFilePath);
}
I don't know if it is my code or an input error.
The first path of your sample is actually matching the regex correctly.
To match the second and fourth, you have to allow double backslashes. Just add \\\\? on the right of the previous backslashes in your regex.
To match the third and fourth, you need to make the second group optional. Currently it is used with the operator +. Use * instead.
Therefore if you replace your regex with this one:
String regularExpression = "([a-zA-Z]:)?(\\\\\\\\?[a-zA-Z0-9_.-]+)*\\\\?\\\\?";
it will match all your paths, and nothing more.
If you still can not match your sample data, then there is a problem somewhere else in your code. You can try posting an SSCCE.

Using Regex to analyse Strings in Java

I created a simple quiz program and I am trying to figure out a method to return 3 types of answer's using regex. The 3 answers would be either fully correct, correct (but spelling error) and partially correct, but still awarded being correct.
So for an example, the three strings will be correct from the method comparing to the String "Elephants" : 1. "Elephants", 2. "Elephents", 3. "Elephant".
The 1st string is fully correct, so would return "Correct Answer".
The 2nd string is correct but spelling error ('a' instead of an 'e'), so will return "Correct although spelled Elephants".
The 3rd string is partially correct (No 's' at the end), but will return "Answer accepted"
Could anyone figure out the three types of Regex expressions I could use for this method?
Thanks much appreciated.
There is no regex solution for this, but you can implement a "distance algorithm" to measure the relative similarity of two words. One very common algorithm for this is Levenshtein Distance, or Edit Distance: it tells you how many "editing actions" it would take to go from the answer the user typed in to the correctly spelled answer. Replacing, inserting, or deleting a symbol counts as one action. If the distance is two or less, the answer the user typed in is likely just a spelling error; if the distance is three or more, it's either a very poorly spelled answer, or an incorrect answer (both should be counted as incorrect).
The wikipedia article linked above has pseudocode implementation for the algorithm.
The first regex to match: Elephants
If it doesn't match try Eleph[ae]nt for the second.
If also not, try Elephant.
You could additionally combine it with word end markers.
For testing regexes, this site is really cool: http://gskinner.com/RegExr/
With regexs, you have to try to guess the spelling errors..
Fully Correct Regex:
"Elephants"
Correct although spelled "Elephants" Regex:
"[^E]lephants|E[^l]ephents|El[^e]phants|Ele[^p]hants|Elep[^h]ants|Eleph[^a]nts|Elepha[^n]ts|Elephan[^t]s|Elephant[^s]"
Answer accepted Regex:
"lephants|Eephants|Elphants|Elehants|Elephants|Elephnts|Elephnts|Elephats|Elephans|Elephant"
You could write a small program which automatically generates the regexp which validate your answer and outputs you the case in which your regexp fall
Correct
Correct although misspelled
Answer accepted
For instance, assuming that the correct answer is "Elephants", you could write a routine which test for the second case (Correct although misspelled).
String generateCorrectAltoughMispelledAnswerRegex(final String answer) {
StringBuilder builder = new StringBuilder();
String answer = "Elephants";
for (int i = 0; i < answer.length; i++) {
String mispelled = answer.substring(0, i) + "[^" + char.at(i) + "]" +
(i < length ? answer.substring(i + 1) : "");
answer.append(mispelled);
if (i < length - 1) { answer.append("|"); }
}
String regex = builder.build();
return regex;
}
e.g.: By calling the function generateCorrectAlthoughMispelledAnswerRegex with the argument "Elephants"
generateCorrectAltoughMispelledAnswerRegex("Elephants")
it will generate the regexp to the test for the second case:
"[^E]lephants|E[^l]ephents|El[^e]phants|Ele[^p]hants|Elep[^h]ants|Eleph[^a]nts|Elepha[^n]ts|Elephan[^t]s|Elephant[^s]"
You can do the same for the other cases.

Regexp for a string to contain only letters , numbers and space in Java

Requirement: String should contain only letters , numbers and space.
I have to pass a clean name to another API.
Implementation: Java
I came up with this for my requirement
public static String getCleanFilename(String filename) {
if (filename == null) {
return null;
}
return filename.replaceAll("[^A-Za-z0-9 ]","");
}
This works well for few of my testcase , but want to know am I missing any boundary conditions, or any better way (in performance) to do it.
Additional to comments: i don't think that performance is an issue in a scenario where user input is taken (and a filename shouldn't be that long...).
But concerning your question: you may reduce the number of replacements by adding an additional + in your regex:
[^A-Za-z0-9 ]+
To answer you're direct question, \t fails your method and passes through as "space." Switch to \s ([...\s] and you're good.
At any rate, your design is probably flawed. Instead of arbitrarily dicking with user input, let the user know what you don't allow and make the correction manual.
EDIT:
If the filename doesn't matter, take the SHA-2 hash of the file name and use that. Guaranteed to meet your requirements.

Categories