This is what i am testing my method with that will check a string to see if its valid, i don't even know if matches is what i need to use. but i am trying to use it to check if a string contains only *, |, and spaces.
public class TallyTest {
public static void main(String[] args) {
System.out.println(TallyString.isValidGroup("||**|*|"));
System.out.println("Expected true");
System.out.println(TallyString.evaluateGroup("||**|*|"));
System.out.println("Expected 19");
System.out.println(TallyString.makeGroup(19));
System.out.println("Expected '***||||'");
}
}
public class Test
{
public static void main(String[] args)
{
String s = "GT|!ll22";
if(!s.matches("[*| ]+"))
System.out.println("Incorrect");
}
}
You can use String.matches to check if characters OTHER THAN certain ones that you want were entered.
Related
I have to validate strings with specific conditions using a regex statement. The condition is that every digit is different from each other. So, 123 works but not 112 or 131.
So, I wrote a statement which filters a string according to the condition and prints true once a string fullfies everything, however it only seems to print "true" altough some strings do not meet the condition.
public class MyClass {
public static void main(String args[]) {
String[] value = {"123","951","121","355","110"};
for (String s : value){
System.out.println("\"" + s + "\"" + " -> " + validate(s));
}
}
public static boolean validate(String s){
return s.matches("([0-9])(?!\1)[0-9](?!\1)[0-9]");
}
}
#Vinz's answer is perfect, but if you insist on using regex, then you can use:
public static boolean validate(String s) {
return s.matches("(?!.*(.).*\\1)[0-9]+");
}
You don't need to use regex for that. You can simply count the number of unique characters in the String and compare it to the length like so:
public static boolean validate(String s) {
return s.chars().distinct().count() == s.length();
}
I want to match 2 strings
e.g. I have pre-defined words like wheat, egg, flour etc...
I got the text from OCR like wh3at, agg, f1Our etc...
So wh3at should match wheat OR f1Our should match flour etc..
I have worked on OCR projects where we "normalized" extracted text. You can build regular expressions that match reasonably expected/observed output.
import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args) {
String[] strings = {"wh3at", "f1Our", "f10ur", "agg"};
for (String s : strings)
System.out.println(String.format("%s -> %s", s, normalizeWord(s)));
}
public static String normalizeWord(String unnormalized) {
if (Pattern.compile("(?i)wh(e|3)at").matcher(unnormalized).matches()) {
return "wheat";
} else if (Pattern.compile("(?i)f(1|L)(O|0)ur").matcher(unnormalized).matches()) {
return "flour";
} else if (Pattern.compile("(?i)(a|e)gg").matcher(unnormalized).matches()) {
return "egg";
}
return unnormalized;
}
}
I was using regex to find function start and end stored in string in java. But was unable to get end index.
String regexPart1 = "((public)|(private)|(protected)) [a-zA-Z_0-9\\<\\>\\,]+ ";
String regexPart2 = "\\(.*\\) (throws .*)?\\{.*}$";
Pattern pattern = Pattern.compile(regexPart1+"run"+regexPart2);
Matcher matcher = pattern.matcher(toEval);
while (matcher.find()) {
System.out.println(" Found: " + matcher.group());
}
With
toEval = "public class ClassEval{public static initialize() throws Exception(){System.out.println("Initialize");}public static void run() throws Exception{System.out.println("This should come only")}public static void main(String[] args){System.out.println("Hello");}}";
Expected output:
Found: public static void run(){System.out.println("This should come only")}
Output coming:
Found: public static void run(){System.out.println("This should come only")}public static void main(String[] args){System.out.println("Hello");}}
* is a greedy quantifier, meaning {.*} will match everything from the first { until the last }. Change it to {.*?} if you want it to stop at the first }. Of course it still won't be able to identify nested braces, but that's a whole other issue.
i need help to substring a string when a a substring occurs.
Example
Initial string: 123456789abcdefgh
string to substr: abcd
result : 123456789
I checked substr method but it accept index position value.I need to search the occurrence of the substring and than pass the index?
If you want to split the String from the last number (a), then the code would look like this:
you can change the "a" to any char within the string
package nl.testing.startingpoint;
public class Main {
public static void main(String args[]) {
String[] part = getSplitArray("123456789abcdefgh", "a");
System.out.println(part[0]);
System.out.println(part[1]);
}
public static String[] getSplitArray(String toSplitString, String spltiChar) {
return toSplitString.split("(?<=" + spltiChar + ")");
}
}
Bear in mind that toSplitString.split("(?<=" + spltiChar + ")"); splits from the first occurrence of that character.
Hope this might help:
public static void main(final String[] args)
{
searchString("123456789abcdefghabcd", "abcd");
}
public static void searchString(String inputValue, final String searchValue)
{
while (!(inputValue.indexOf(searchValue) < 0))
{
System.out.println(inputValue.substring(0, inputValue.indexOf(searchValue)));
inputValue = inputValue.substring(inputValue.indexOf(searchValue) +
searchValue.length());
}
}
Output:
123456789
efgh
Use a regular expression, like this
static String regex = "[abcd[.*]]"
public String remove(String string, String regex) {
return string.contains(regex) ? string.replaceAll(regex) : string;
}
I need to match if filenames have exactly 2 underscores and extension 'txt'.
For example:
asdf_assss_eee.txt -> true
asdf_assss_eee_txt -> false
asdf_assss_.txt -> false
private static final String FILENAME_PATTERN = "/^[A-Za-z0-9]+_[A-Za-z0-9]+_[A- Za-z0-9]\\.txt";
does not working.
You just need to add + after the third char class and you must remove the first forward slash.
private static final String FILENAME_PATTERN = "^[A-Za-z0-9]+_[A-Za-z0-9]+_[A-Za-z0-9]+\\.txt$";
You can use a regex like this with insensitive flag:
[a-z\d]+_[a-z\d]+_[a-z\d]+\.txt
Or with inline insensitive flag
(?i)[a-z\d]+_[a-z\d]+_[a-z\d]+\.txt
Working demo
In case you want to shorten it a little, you could do:
([a-z\d]+_){2}[a-z\d]+\.txt
Update
So lets assume you want to at least one or more characters after the second underscore, before the file extension.
Regex is still not "needed" for this. You could split the String by the underscore and you should have 3 elements from the split. If the 3rd element is just ".txt" then it's not valid.
Example:
public static void main(String[] args) throws Exception {
String[] data = new String[] {
"asdf_assss_eee.txt",
"asdf_assss_eee_txt",
"asdf_assss_.txt"
};
for (String d : data) {
System.out.println(validate(d));
}
}
public static boolean validate(String str) {
if (!str.endsWith(".txt")) {
return false;
}
String[] pieces = str.split("_");
return pieces.length == 3 && !pieces[2].equalsIgnoreCase(".txt");
}
Results:
true
false
false
Old Answer
Not sure I understand why your third example is false, but this is something that can easily be done without regex.
Start with checking to see if the String ends with ".txt", then check if it contains only two underscores.
Example:
public static void main(String[] args) throws Exception {
String[] data = new String[] {
"asdf_assss_eee.txt",
"asdf_assss_eee_txt",
"asdf_assss_.txt"
};
for (String d : data) {
System.out.println(validate(d));
}
}
public static boolean validate(String str) {
if (!str.endsWith(".txt")) {
return false;
}
return str.chars().filter(c -> c == '_').count() == 2;
}
Results:
true
false
true
Use this Pattern:
Pattern p = Pattern.compile("_[^_]+_[^_]+\\.txt")
and use .find() instead of .match() in the Matcher:
Matcher m = p.matcher(filename);
if (m.find()) {
// found
}