I need to use validation where input value should end with "Type" So I came up with Type$ regex, but it is failing for correct values. Here is how I am using this in Pattern annotation in my code
#Pattern(regexp = REGISTRY_CONFIG_TYPE_FORMAT,message = REGISTRY_CONFIG_TYPE_ERROR)
#ApiModelProperty(name = "registryConfigType", dataType = "String", value = "OccasionType", example = "OccasionType", required = true)
private String registryConfigType;
the constant value
REGISTRY_CONFIG_TYPE_FORMAT = "Type$"
when I am passing value like : OccasionType, I am getting the error message. But on regex101 it's working fine. Not sure where is the problem.
following is the error log which I am getting
Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.macys.registry.dataobject.v1.response.RegistryAppResponse<java.lang.Object> com.macys.registry.controller.RegistryConfigController.updateConfig(com.macys.registry.dataobject.v1.request.UpdateRegistryConfigRequest): [Field error in object 'updateRegistryConfigRequest' on field 'registryConfigType': rejected value [OccasionType]; codes [Pattern.updateRegistryConfigRequest.registryConfigType,Pattern.registryConfigType,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [updateRegistryConfigRequest.registryConfigType,registryConfigType]; arguments []; default message [registryConfigType],[Ljavax.validation.constraints.Pattern$Flag;#20999237,Type$]; default message [Registry Config Type Should Not Be Null And Should End With [Type]]] ]
Try this for your case
REGISTRY_CONFIG_TYPE_FORMAT= ".*Type$";
It may not be 100% clear from the javadoc, but the regexp must match. In other words, the entire input must be captured by the regexp. A simple fix: .*Type. Note that the $ is unnecessary, as that's already implied by the matching.
Your regex would be valid if find where used instead of match.
Try changing you constant to:
REGISTRY_CONFIG_TYPE_FORMAT = "\\w*Type\\b";
From RegExr:
\w Word. Matches any word character (alphanumeric & underscore).
* Quantifier. Match 0 or more of the preceding token.
T Character. Matches a "T" character (char code 84). Case sensitive.
y Character. Matches a "y" character (char code 84). Case sensitive.
p Character. Matches a "p" character (char code 84). Case sensitive.
e Character. Matches a "e" character (char code 84). Case sensitive.
\b Word boundary. Matches a word boundary position between a word character and non-word character or position (start / end of string).
Hope this will help.
Related
I am looking for regex which can help me replace strings like
source=abc/task=cde/env=it --> source='abc'/task='cde'/env='it'
To be more precise, I want to replace a string which starts with = and ends with either / or end of the string with ''
Tried code like this
"source=abc/task=cde/env=it".replaceAll("=(.*?)/","'$1'")
But that results in
source'abc'task'cde'env=it
Using lookahead and look behind:
(?<==)([^/]*)((?=/)|$)
Lookbehind allows you to specify what comes before your match. In this case an equals: (?<==).
The main match in my regex looks for any non-slash character, zero or more times: ([^/]*)
Lookahead allows you to specify what comes after your match. In this case, a slash: (?=/).
The $ matches the end of the line, so that the last item in your test data becomes quoted. ((?=/)|$) combines with this with the lookahead, meaning "either a slash comes after the match or this is the end of the line".
Here it is in action in a test.
#Test
public void test_quote_items() {
String regex = "(?<==)([^/]*)((?=/)|$)";
String actual = "source=abc/task=cde/env=it".replaceAll(regex,"'$1'");
String expected = "source='abc'/task='cde'/env='it'";
assertEquals(expected, actual);
}
Try
String input = "source=abc/task=cde/env=it".replaceAll("=(.*?)(/|$)","='$1'/");
The problems I found are that you are not replacing the =
and also the / is not there for the end of String, that also needs to be replaced when found.
output
source='abc'/task='cde'/env='it'/
If you don't want the last '/', that is trivial to remove isn't it.
I'm trying to use ESAPI in my existing project.
I'm getting an error while trying to use ESAPI.validator().getValidInput() method for SafeString type.
The following is an auto defined Regex, contained in the validation.properties file:
Validator.SafeString=^[.\\p{Alnum}\\p{Space}]{0,1024}$
I assumed that the max length is 1024.
This is my code:
ESAPI.validator().getValidInput("Validationofinput",_appendToSelect,"SafeString",1024, true)
However, I received the following error:
WARN IntrusionDetector - [SECURITY FAILURE Anonymous:null#unknown ->
/ExampleApplication/IntrusionDetector] Invalid input:
context=Validationofinput,
type(SafeString)=^[.\p{Alnum}\p{Space}]{0,1024}$, input=and
ProductCategory like '%test_%'
org.owasp.esapi.errors.ValidationException: Validationofinput: Invalid
input. Please conform to regex ^[.\p{Alnum}\p{Space}]{0,1024}$ with a
maximum length of 1024 at
org.owasp.esapi.reference.validation.StringValidationRule.checkWhitelist(StringValidationRule.java:144)
at
org.owasp.esapi.reference.validation.StringValidationRule.checkWhitelist(StringValidationRule.java:160)
at
org.owasp.esapi.reference.validation.StringValidationRule.getValid(StringValidationRule.java:284)
at
org.owasp.esapi.reference.DefaultValidator.getValidInput(DefaultValidator.java:214)
at
org.owasp.esapi.reference.DefaultValidator.getValidInput(DefaultValidator.java:185)
Can someone tell me what I did wrong?
Okay,
This is failing because your input doesn't match the regular expression, not because of a length violation.
The Posix standard specifies that \p{Alnum} corresponds to the regex [a-zA-Z0-9] and \p{Space} corresponds to \s. In your case, your input will fail because of the characters: ' and % and _
^[.\\p{Alnum}\\p{Space}]{0,1024}$:
^ == At the beginning of the line
[ == Start a character class, match any of the following characters in any order
. == Match an ASCII period
\\p{Alnum} == Match any ASCII alphabet character or number, upper or lower case.
\\p{Space} == Match any ASCII whitespace
] == End character class
{0,1024} == Match any number of characters from 0 to 1024
$ == All the way until the end of the line.
I would like to find a pattern where [^#$%_-]COMMENT should be true and string "COMMENT" should also be true.
Case 1 : #COMMENT true
Case 2 : #COMMENT false
Case 3 : COMMENT true
For Case 3 i am getting false
My regular expression is [^#\'\"$%_-|]COMMENT
Try a lookbehind assertion (?<![#$%'_"-])COMMENT
Stringed "(?<![#$%'_\"-])COMMENT"
If you actually want to match the character before, as well as comment,
it would be this \S?(?<![#$%_-])COMMENT
Stringed "\\S?(?<![#$%'_\"-])COMMENT"
Load up the class with [stuff not allowed].
When you use the class inside a negative assertion, you don't need the
negated class [^] anymore since it is positively addressed as not allowed
via a negative assertion.
You can use this.
^[^#$%-]?COMMENT$
[^#$%-]? -> not contain any of these characters.
String c1 = "#COMMENT";
String c2 = "#COMMENT";
String c3 = "COMMENT";
System.out.println(c1.matches("^[^#$%-]?COMMENT$"));
System.out.println(c2.matches("^[^#$%-]?COMMENT$"));
System.out.println(c3.matches("^[^#$%-]?COMMENT$"));
the corrrect java regex for our case would be
String regex = "[^#\'\\"\$%\-|]COMMENT"
You can test the output at regex101
I get a String from the JSP, containing [", e.g.
["Bulgaria
I would like to replace all the [" occurrences for [', but I don't know exactly how to do it...
I just tried:
str = str.replaceAll("[\\\"", "['");
with the result
java.util.regex.PatternSyntaxException: Unclosed character class near index 2 [\"
and
html = html.replaceAll("[\"", "['");
with the result
java.util.regex.PatternSyntaxException: Unclosed character class near index 1 [" ^
any help will be appreciated
Try this:
str.replaceAll("\\[\"", "['");
You need \\ to escape in java regex and [ is a special character in java regex, thus the \\ in front of it. " is a special character in strings so you only need one \ to escape it.
"Test[\"".replaceAll("\\[\"", "['"); // Test['
I want to split the string
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
to
name
employeeno
dob
joindate
I wrote the following java code for this but it is printing only name other matches are not printing.
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
Pattern pattern = Pattern.compile("\\[.+\\]+?,?\\s*" );
String[] split = pattern.split(fields);
for (String string : split) {
System.out.println(string);
}
What am I doing wrong here?
Thank you
This part:
\\[.+\\]
matches the first [, the .+ then gobbles up the entire string (if no line breaks are in the string) and then the \\] will match the last ].
You need to make the .+ reluctant by placing a ? after it:
Pattern pattern = Pattern.compile("\\[.+?\\]+?,?\\s*");
And shouldn't \\]+? just be \\] ?
The error is that you are matching greedily. You can change it to a non-greedy match:
Pattern.compile("\\[.+?\\],?\\s*")
^
There's an online regular expression tester at http://gskinner.com/RegExr/?2sa45 that will help you a lot when you try to understand regular expressions and how they are applied to a given input.
WOuld it be better to use Negated Character Classes to match the square brackets? \[(\w+\s)+\w+[^\]]\]
You could also see a good example how does using a negated character class work internally (without backtracking)?