Basically I have a simple String Where I need to explicitly restrict characters other than a-zA-Z0-9. Before I mention what is wrong here is how I am doing it.
Pattern p = Pattern.compile("[&=]");
Matcher m = p.matcher("Nothing is wrong");
if (m.find()){
out.print("You are not allowed to have &=.");
return;
}
Pattern p1 = Pattern.compile("[a-zA-Z0-9]");
Matcher m1 = p1.matcher("Itissupposetobeworking");
if (m1.find()){
out.print("There is something wrong.");
return;
}
The first one works fine, But on the second matcher m1 always gets to execute if(m1.find()) even though it doesn't contain any character other than specified in the pattern.
I also tried Pattern p1 = Pattern.compile("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]") But still have the same trouble.
and if you might wanna tell, which is better between String.matches(["a-zA-Z0-9"]); or the way I am using above?
Thanks in advance.
[a-zA-Z0-9] tries to match alphanumeric characters.
So, you will get "There is something wrong." to be printed, if you have a alphanumeric character in the input character sequence of matcher().
Change it to [^a-zA-Z0-9] and try.
This tries to match non-alphanumeric characters. So, you will get expected result.
You seem to want to find a partial match in a string that contains a character other than an alphanumeric character:
Pattern p1 = Pattern.compile("[^a-zA-Z0-9]");
or
Pattern p1 = Pattern.compile("\\P{Alnum}");
The [^a-zA-Z0-9] pattern is a negated character class that matches any char other than the ones defined in the class. So, if a string contains any chars other than ASCII letters or digits, your if (m1.find()) will get triggered and the message will appear.
Note that the whole negated character class can be replaced with a predefined character class \P{Alnum} that matches any char other than alphanumeric. \p{Alnum} matches any alphanumeric character and \P{Alnum} is the reverse class.
If you use the isAlphanumeric Method of org.apache.commons.lang.StringUtils yourcode become much more readable. So you need to write
if (!StringUtils.isAlphanumeric("Itissupposetobeworking"))
instead of
Pattern p1 = Pattern.compile("[a-zA-Z0-9]");
Matcher m1 = p1.matcher("Itissupposetobeworking");
if (!m1.find()){
When above expression finds a matching it prints "There is something wrong." but if you want to restrict then Use below code.
Pattern p1 = Pattern.compile("a-zA-Z0-9");
String a = "It$issupposetobeworking";
Matcher m1 = p1.matcher(a);
if (m1.find()){
System.out.print("There is something wrong.");
}
else
{
System.out.println("Everything is fine");
}
If you want the same code to be working with same regular expression in that scenario use this code.
Pattern p1 = Pattern.compile("[a-zA-Z0-9]");
Matcher m1 = p1.matcher("Itissupposetobeworking");
if (!(m1.find())){
out.print("There is something wrong.");
return;
}
Related
I am trying to extract everything that is after this string path /share/attachments/docs/. All my strings are starting with /share/attachments/docs/
For example: /share/attachments/docs/image2.png
Number of characters after ../docs/ is not static!
I tried with
Pattern p = Pattern.compile("^(.*)/share/attachments/docs/(\\d+)$");
Matcher m = p.matcher("/share/attachments/docs/image2.png");
m.find();
String link = m.group(2);
System.out.println("Link #: "+link);
But I am getting Exception that: No match found.
Strange because if I use this:
Pattern p = Pattern.compile("^(.*)ABC Results for draw no (\\d+)$");
Matcher m = p.matcher("ABC Results for draw no 2888");
then it works!!!
Also one thing is that in some very rare cases my string does not start with /share/attachments/docs/ and then I should not parse anything but that is not related directly to the issue, but it will be good to handle.
I am getting Exception that: No match found.
This is because image2.png doesn't match with \d+ use a more appropriate pattern like .+ assuming that you want to extract image2.png.
Your regular expression will then be ^(.*)/share/attachments/docs/(.+)$
In case of ABC Results for draw no 2888, the regexp ^(.*)ABC Results for draw no (\\d+)$ works because you have several successive digits at the end of your String while in the first case you had image2.png that is a mix of letters and digits which is the reason why there were no match found.
Generally speaking to avoid getting an IllegalStateException: No match found, you need first to check the result of find(), if it returns true the input String matches:
if (m.find()) {
// The String matches with the pattern
String link = m.group(2);
System.out.println("Draw #: "+link);
} else {
System.out.println("Input value doesn't match with the pattern");
}
The regular expression \d+ (expressed as \\d+ inside a string literal) matches a run of one or more digits. Your example input does not have a corresponding digit run, so it is not matched. The regex metacharacter . matches any character (+/- newline, depending on regex options); it seems like that may be what you're really after.
Additionally, when you use Matcher.find() it is unnecessary for the pattern to match the whole string, so it is needless to include .* to match leading context. Furthermore, find() returns a value that tells you whether a match to the pattern was found. You generally want to use this return value, and in your particular case you can use it to reject those rare non-matching strings.
Maybe this is more what you want:
Pattern p = Pattern.compile("/share/attachments/docs/(.+)$");
Matcher m = p.matcher("/share/attachments/docs/image2.png");
String link;
if (m.find()) {
link = m.group(1);
System.out.println("Draw #: " + link);
} else {
link = null;
System.out.println("Draw #: (not found)");
}
I am trying to write a regex to accept latin/UCS2 characters. But I am getting error while doing that. In the following code, the 'text1' should pass for the pattern. I am still working on this. can anyone please help me in fxing this?
String text1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz !\"#$%&'()*+,-./:;<=>?#"
+ "{|}~¡ ";
String pattern = "^[a-zA-Z0-9\\*\\?\\$\\[\\]\\(\\)\\|\\{\\}\\/\\'\\#\\~\\.,;\"\\<=\\>-#%&!+:~¡ ]+$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text1);
if (m.find()) {
System.out.println("true");
}
What is not working? Is the pattern not matching or is there an error message?
What I see first you have escaped so many characters, that doesn't need to be escaped and an important one is not escaped.
In a character class there are only a few characters that have a special meaning []- and ^ when it is at the first position. You haven't escaped the -, this can cause an error, so try:
String pattern = "^[a-zA-Z0-9*?$\\[\\]()|{}/'#~.,;\"<=>\\-#%&!+:~¡ £¤¥ §¿ ÄÅÆÇÉÑÖØÜßàäåæ èéìñòöøùü ]+$";
The next thing is: Have a look at Unicode Properties/Scripts. You can e.g. use \\p{L} to match a letter in any language.
String pattern = "^[\\p{L}\\p{M}0-9*?$\\[\\]()|{}/'#~.,;\"<=>\\-#%&!+:~¡ £¤¥ §¿]+$";
Would match all letters you had in your class and more!
I have strings with parentheses and also escaped characters. I need to match against these characters and also delete them. In the following code, I use matches() and replaceAll() with the same regex, but the matches() returns false, while the replaceAll() seems to match just fine, because the replaceAll() executes and removes the characters. Can someone explain?
String input = "(aaaa)\\b";
boolean matchResult = input.matches("\\(|\\)|\\\\[a-z]+");
System.out.printf("matchResult=%s\n", matchResult);
String output = input.replaceAll("\\(|\\)|\\\\[a-z]+", "");
System.out.printf("INPUT: %s --> OUTPUT: %s\n", input, output);
Prints out:
matchResult=false
INPUT: (aaaa) --> OUTPUT: aaaa
matches matches the whole input, not part of it.
The regular expression \(|\)|\\[a-z]+ doesn't describe the whole word, but only parts of it, so in your case it fails.
What matches is doing has already been explained by Binyamin Sharet. I want to extend this a bit.
Java does not have a "findall" or a "g" modifier like other languages have it to get all matches at once.
The Java Matcher class knows only two methods to use a pattern against a string (without replacing it)
matches(): matches the whole string against the pattern
find(): returns the next match
If you want to get all things that fits your pattern, you need to use find() in a loop, something like this:
Pattern p = Pattern
.compile("\\(|\\)|\\\\[a-z]+");
Matcher m = p.matcher(text);
while(m.find()){
System.out.println(m.group(0));
}
or if you are only interested if your pattern exists in the string
if (m.find()) {
System.out.println(m.group());
} else {
System.out.println("not found");
}
This seems like a well known title, but I am really facing a problem in this.
Here is what I have and what I've done so far.
I have validate input string, these chars are not allowed :
&%$###!~
So I coded it like this:
String REGEX = "^[&%$###!~]";
String username= "jhgjhgjh.#";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(username);
if (matcher.matches()) {
System.out.println("matched");
}
Change your first line of code like this
String REGEX = "[^&%$##!~]*";
And it should work fine. ^ outside the character class denotes start of line. ^ inside a character class [] means a negation of the characters inside the character class. And, if you don't want to match empty usernames, then use this regex
String REGEX = "[^&%$##!~]+";
i think you want this:
[^&%$###!~]*
To match a valid input:
String REGEX = "[^&%$##!~]*";
To match an invalid input:
String REGEX = ".*[&%$##!~]+.*";
I'm a Java user but I'm new to regular expressions.
I just want to have a tiny expression that, given a word (we assume that the string is only one word), answers with a boolean, telling if the word is valid or not.
An example... I want to catch all words that is plausible to be in a dictionary... So, i just want words with chars from a-z A-Z, an hyphen (for example: man-in-the-middle) and an apostrophe (like I'll or Tiffany's).
Valid words:
"food"
"RocKet"
"man-in-the-middle"
"kahsdkjhsakdhakjsd"
"JESUS", etc.
Non-valid words:
"gipsy76"
"www.google.com"
"me#gmail.com"
"745474"
"+-x/", etc.
I use this code, but it won't gave the correct answer:
Pattern p = Pattern.compile("[A-Za-z&-&']");
Matcher m = p.matcher(s);
System.out.println(m.matches());
What's wrong with my regex?
Add a + after the expression to say "one or more of those characters":
Escape the hyphen with \ (or put it last).
Remove those & characters:
Here's the code:
Pattern p = Pattern.compile("[A-Za-z'-]+");
Matcher m = p.matcher(s);
System.out.println(m.matches());
Complete test:
String[] ok = {"food","RocKet","man-in-the-middle","kahsdkjhsakdhakjsd","JESUS"};
String[] notOk = {"gipsy76", "www.google.com", "me#gmail.com", "745474","+-x/" };
Pattern p = Pattern.compile("[A-Za-z'-]+");
for (String shouldMatch : ok)
if (!p.matcher(shouldMatch).matches())
System.out.println("Error on: " + shouldMatch);
for (String shouldNotMatch : notOk)
if (p.matcher(shouldNotMatch).matches())
System.out.println("Error on: " + shouldNotMatch);
(Produces no output.)
This should work:
"[A-Za-z'-]+"
But "-word" and "word-" are not valid. So you can uses this pattern:
WORD_EXP = "^[A-Za-z]+(-[A-Za-z]+)*$"
Regex - /^([a-zA-Z]*('|-)?[a-zA-Z]+)*/
You can use above regex if you don't want successive "'" or "-".
It will give you accurate matching your text.
It accepts
man-in-the-middle
asd'asdasd'asd
It rejects following string
man--in--midle
asdasd''asd
Hi Aloob please check with this, Bit lengthy, might be having shorter version of this, Still...
[A-z]*||[[A-z]*[-]*]*||[[A-z]*[-]*[']*]*