I am trying to validate a RegEx string in Java but i cant get it to work properly. I am attempting to make sure the the following string "AB10XY" is always contained with the textField when performing a search.
I have the following line of code which ensures that AB and XY are in the textField but not the number:
boolean checkChar = ((textField.getText().contains("AB")) && (textField.getText().contains("XY")));
I would prefer to have something like :
boolean checkChar = ((textField.getText().contains("AB[\\d]{2}XY")));
You can try this way
boolean checkChar = ((textField.getText().matches(".*?AB[\\d]{2}XY.*")));
I'm guessing the number isn't alway 10, so you should use something like this:
boolean checkChar = textField.getText().matches(".*AB[\\d]{2}XY.*");
Use package java.util.regex to handle RegEx
boolean checkChar = java.util.regex.Pattern.compile("AB[\\d]{2}XY")
.matcher(textField.getText()).find();
Contains method doesn't support regex..You can use matches method
textField.getText().matches(".*AB\\d{2}XY.*");
Related
I have written a function that checks if a string contains certain words but am not happy with the way the code looks
SO currently i have
private String url = "validator=http://url.com;useraccount=sf4cdamloci;licence=39I8934U401;addedon=343443334;serial=7QW0-5TU8-YN9P-G4FZ;limit=123;days=10"
private String musthave ="validator,useraccount,licence,addedon,serial,limit,days"
So i wanted to check that the url contains the must have words in the string. That eg url must have validator, useraccount, licence.....
SO i have tried the following
Boolean has_validator = false;
Boolean has_licence = false;
.....//others with has_ prefix
String[] split_url = url.split(";")
for(String key_item : split_url){
String[] splitteditem = key_item.split("=");
if (splitteditem[0].equalsIgnoreCase("validator")){
has_validator = true;
}
if (splitteditem[0].equalsIgnoreCase("useraccount")){
has_useraccount = true;
}
....others as well
}
Then later i can easily check
if(has_useraccount && has_...)
The above solution works buts its not scalable as whenever i include a new must have ill have to edit my function.
Is there a better way to achieve this. Am still new to java. I have checked on regex but still i can figure our on how to achieve this.
How do i proceed
Don't use a String to represent a set of Strings. Use... a Set of String: Set<String>. Or at least an array of strings.
Then just use a loop. If any of the word in the set isn't contain in the text, you can immediately return false. If you have never returned false in the loop, then all the words are contained in the text, and you can return true.
Pseudo code:
for each word in the set
if the word is not in the text, return false
end for
return true
If you have a Collection of must-have strings, then you can do something simple like:
mustHave.stream().allMatch(url::contains)
My example isn't doing a case-insensitive check, but you get the idea.
Example: This is my string,
String sample = "s5656";
If the first character of the string contains 's' or 'p' or 'r' means i should remove the character,Otherwise i have to
return the original string.
Is there any optimized way to do that like "regex" or "StringUtils" in apache common?
Why do you want to add 3rd party jar for this kind of simple requirement? You can try as follows
String sample = "s5656";
if(sample.startsWith("s")||sample.startsWith("r")||sample.startsWith("p")){
// do necessary
}else{
// do necessary
}
String#startsWith()
A simple regex could solve your problem :
public static void main(String[] args) {
String s = "s5656s";
System.out.println(s.replaceFirst("^[spr]", "")); // a String which begins with s,p or r
}
O/P:
5656s
PS: regex here leads to smaller/simpler but inefficient code. Use Ruchira's answer for a rather long but efficient code. :)
^(s|p|r)
Try this.Use yourString.replaceAll() / replaceFirst() with empty string.Use m.
See demo.
http://regex101.com/r/dZ1vT6/49
I should go for replaceAll function with multiline modifier (?m).
String s = "s5656s\n" +
"r878dsjhj\n" +
"fshghg";
System.out.println(s.replaceAll("(?m)^[spr]", ""));
Output:
5656s
878dsjhj
fshghg
I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);
I want to validate a string which donot have numeric characters.
If my string is "javaABC" then it must be validated
If my string is "java1" then it must not be validated
I want to restrict all the integers.
Try this:
String Text = ...;
boolean HasNoNumber = Text.matches("^[^0-9]*$");
'^[^0-9]*$' = From Start(^) to end ($), there are ([...]) only non(^) number(0-9). You can use '\D' as other suggest too ... but this is easy to understand.
See more info here.
You can use this:
\D
"\D" matches non-digit characters.
Here is one way that you can search for a digit in a String:
public boolean isValid(String stringToValidate) {
if(Pattern.compile("[0-9]").matcher(stringToValidate).find()) {
// The string is not valid.
return false;
}
// The string is valid.
return true;
}
More detail is here:
http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html
The easiest to understand is probably matching for a single digit and if found fail, instead of creating a regexp that makes sure that all characters in the string are non-digits.
I want to ask if anyone knows whether Java has built in library for doing something like the following.
For instance,
I have 2 Strings which are:
String a = "Yeahh, I love Java programming.";
String b = "love";
I want to check whether the String b which contains "love" is part of the tokens in the String a. Hence, I want to ask are there any Java API to do so?
I want something like,
a.contains (b) <--------- Return true result
Are there any???
because,,,,if there's no Java API for that, I would write my own algorithm then.
Thanks in advance for any helps..^^
The suggestions so far (indexOf, contains) are all fine if you just want to find substrings. However, given the title of your question, I assume you actually want to find words. For instance, if asked whether "She wore black gloves" contained "love" my guess is you'd want the answer to be no.
Regular expressions are probably the best way forward here, using a word boundary around the word in question:
import java.util.regex.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(containsWord("I love Java", "love"));
System.out.println(containsWord("She wore gloves", "love"));
System.out.println(containsWord("start match", "start"));
System.out.println(containsWord("match at end", "end"));
}
public static boolean containsWord(String input, String word)
{
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
return pattern.matcher(input).find();
}
}
Output:
true
false
true
true
string strToCheck = "check me";
int firstOccurence = strToCheck .indexOf("me");
//0 if no any
the method contains(CharSequence s) exist in the class String.
So your a.contains(b) will work
You can use the indexOf() function in the String library to check for it:
if(a.indexOf(b)>=0)
return true;
Yes, there is: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence).
If you want to find the words will be quite easy, you just have to use split.
//Split to an array using space as delimiter
String[] arrayOfWords = a.split(" ");
And then you'll compare like:
"love".equalsIgnoreCase(arrayOfWords[i]);
something like that, you get the idea