Regex pattern matching using #Pattern annotation in Spring Boot [duplicate] - java

This question already has an answer here:
All characters in a string must match regex
(1 answer)
Closed 12 days ago.
I want to accept only those titles which don't contain following characters: \/:*?"<>|
I tried using the below method, but it didn't work for me
#Pattern(regexp = "[^\\/:*?\"<>|]", message = "Not valid")
private String title;
I am new in pattern matching so please help me with the solution...

A good start. The #Pattern annotation defines the pattern the underlying String should match.
The annotated CharSequence must match the specified regular expression. The regular expression follows the Java regular expression conventions see Pattern.
In your case, you only list the characters, that should not be matched. You should define a pattern to be matched instead.
Try this one (see Regex101 for a demo) and notice the + quantifier.
^[^\/:*?\"<>|]+$
In Java, mind the escaping:
#Pattern(regexp = "^[^\\/:*?\\\"<>|]+$", message = "Not valid")
private String title;

Related

Java Regex match string if the patterns ends with ; or nothing [duplicate]

This question already has answers here:
Alternation operator inside square brackets does not work
(2 answers)
In regex, match either the end of the string or a specific character
(2 answers)
Closed 3 years ago.
[Posting this question because I could not find any question matching my scenario, please point me to the post if this is already discussed, I will delete this post.]
Trying to create a regex to match string app=myApp in long string separated by either , or ;.
My regex fails if the patterns is at end and not terminated by by either , or ;.
This is the regex I have used: [^.][app|APP]=(.*?)[,|;] this works for the following strings:
env=prod;app=myApp;app.secure=yes
app=myApp;app.secure=yes
But does not work for following:
env=prod;app=myApp
app=myApp
Here is my code:
Pattern pattern = Pattern.compile("[^.][app|APP]=(.*?)[,|;]");
Matcher matcher = pattern.matcher(stringVar);
if (matcher.find()) {
return matcher.group(1);
}
I have also tried:
[^.][app|APP]=(.*?)[,|;|$]
but still no luck.
Try Regex: (?:app|APP)=(.*?)(?=,|;|$)
Demo

Java Regex to not allow String Special Characters

I want to set a password which do not allow specific special characters like
-_\
and my regular expression is as follows
PatternCompiler compiler = new Perl5Compiler();
PatternMatcher matcher = new Perl5Matcher();
pattern = compiler.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])([A-Za-z0-9-/-~][^\\\\\\\\_\-]*)$");
It is working partially. If i place unwanted special characters between the string and start of the string still it is matching the password
P#ssword123 --correct
-password#123 --it should not match
-passowrd"11 --it should not match
\password123 --it should not match
_#111Password --it should not match
p#sswor"123 --correct
Any where in the string if i find -_\ regular expression should not match.
Using Apache api for matching pattern in java
Here is a general regex you can try:
^((?=[A-Za-z])(?![_\-]).)*$
^^ whitelist ^^ blacklist
You can include both a positive and negative lookahead assertion which will check for the presence or absence of a character class. Something like the following might work for you:
String password = "-passw#rd";
// nice trick: by placing hyphen at the end of the character class,
// we don't need to escape it
String pattern = "^((?=[A-Za-z0-9#])(?![_\\\\-]).)*$";
if (password.matches(pattern)) {
System.out.println("valid");
}
else {
System.out.println("not valid");
}
That being said, I would strongly recommend that you search around for regular expressions for passwords. This is a known and old problem, and a lot of good work has already been done in this area, including on Stack Overflow.

Why I must specify whole string in Java regular expression? [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 6 years ago.
Suppose, I have a string:
String str = "some strange string with searched symbol";
And I want to search in it some symbols, suppose it will be "string". So we have a following:
str.matches("string"); //false
str.matches(".*string.*"); //true
So, as stated in the title, why I must specify whole string in Java regular expression?
Java documentation says:
public boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
It doesn't says
Tells whether or not this whole string matches the given regular expression.
For example, in the php it would be:
$str = "some strange string with searched symbol";
var_dump(preg_match('/string/', $str)); // int(1)
var_dump(preg_match('/.*string.*/', $str)); //int(1)
So, both of the regex's will be true.
And I think this is correct, because if I want to test whole string I would do str.matches("^string$");
PS: Yes, I know that is to search a substring, simpler and faster will be to use str.indexOf("string") or str.contains("string"). My question regards only to Java regular expression.
UPDATE: As stated by #ChrisJester-Young (and #GyroGearless) one of the solutions, if you want to search regex that is part of a subject string, is to use find() method like this:
String str = "some strange string with searched symbol";
Matcher m = Pattern.compile("string").matcher(str);
System.out.println(m.find()); //true
matches always matches the whole input string. If you want to allow substrings to match, use find.
As the documentation you suggest,
public boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
What it means is whether that string matches with the given regex. i.e. matches verifies whether your string is an instance of the given regex.
not whether it contains a substring which is an instance of the given regex. As Chris suggested you can use find instead or for your problem you can use contains.
Yes, as you already know (now) that matches() will return true only for the complete string.
But, in your update, you have stated that:
As stated by #ChrisJester-Young (and #GyroGearless) the only solution, if you want to search regex that is part of a subject string, is to use find() method...
I would like to say that using find() is not the only solution. There is at least one more, which I know :
String str = "some strange string with searched symbol";
boolean found = str.split("string").length>1;
System.out.println(found);
This prints true. And this will work for all regular expressions. Though this is not the way to do it, and is instead a hack.
There may be many more solutions.

Regex to use in Pattern annotation for dot appearing maximum once.

I want a Regex that I want to use in Java Pattern annotation to match with a String that contains maximum one dot.
I found a Regex that works outside Java here:
https://stackoverflow.com/a/37890308/1787314
I am not sure why but the Regex doesn't seem to work when passed in the Pattern annotation.
#Pattern(regex = "^[^.]*(?:\\.[^.]*)?$")
private String name;
This is the behavior that I am expecting.
Nick.Div -- Matches
NickDiv -- Matches
Nick.Div. -- Doesn't Match
Nic.k.Div -- Doesn't Match
I tried manipulating the Regex a bit inside the annotation but all failed.
I would really appreciate some help on this.
Use this pattern:
"^[^.]*\\.[^.]*$"
Online Demo
" delimiter
^ first of string
[^.]* a character class which matches zero or more of everything except .
\\. matches a dot . literally
$ end of string

Regular Expression Java (punctuations) [duplicate]

This question already has answers here:
How can I use "." as the delimiter with String.split() in java [duplicate]
(8 answers)
Closed 9 years ago.
I would like to identify 2 types of patterns in a string. They are:
1) xxx:xxxxxxx:xxx.xx
2) xxx.xxx.xxx.xx:xxxxxxxxxx
Basically I want to know how to identify a literal "." in a string.
Since . means any character, what should I type when I am looking for a literal "."?
You can either escape the . like this \\.
or
use it within character class like this [.]
Try using, String [] stringArray = string.split("\\.");
escaping the "."
And then int periods = stringArray.length;
Telling you how many periods there are in your "String"
Just a start on escaping characters. I am unsure what your question is asking so I just gave an intro to escaping.
good luck
String text ="xxx.xxx.xxx.xx:xxxxxxxxxx";
String patternString = "(.*)(\\.)(.*)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
boolean matches = matcher.matches();
System.out.println(matches);
}

Categories