Regular expression to check invalid input - java

I need to parse a a string which contains the query for the database.
The valid strings can be the following :
Status:OPEN,PENDING
Status:OPEN
Status:PENDING
Status:REJECTED
type:SMALL
type:BIG
weight>100
The following is not valid :
weight:100<PENDING
My first try was this in Java:
Pattern p = Pattern.compile("(\\w+?)(:|<|>)(\\w+)(|,)*(\\w+)*$");
Obviously, it fails to parse the last statement correctly.

I think that validating this with a regexpression is a hrad thing.
But you can try this expression:
"([\\w]+)(:(([A-Z]+)|([A-Z]+,([A-Z]+)))|(>[0-9]+))"
It worked for me in a online regexpression tester for your inputs

I created this expression for your requirement:
Pattern pattern = Pattern.compile("((Status:(OPEN|PENDING|OPEN,PENDING|REJECTED))|(type:(SMALL|BIG))|(weight[<>]\\d+))");
anything else matches invalid status, types, etc.
For example:
These are all invalid:
Status>100
type:REJECTED
weight:100
Hope this helps!

Related

Regex pattern error on API 21(android 5) and below

Android 5 and below getting error from my regex pattern on runtime:
java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 4:
(?<g1>(http|ftp)(s)?://)?(?<g2>[\w-:#])+(?<TLD>\.[\w\-]+)+(:\d+)?((|\?)([\w\-._~:/?#\[\]#!$&'()*+,;=.%])*)*
Here is code sample:
val urlRegex = "(?<g1>(http|ftp)(s)?://)?(?<g2>[\\w-:#])+(?<TLD>\\.[\\w\\-]+)+(:\\d+)?((|\\?)([\\w\\-._~:/?#\\[\\]#!$&'()*+,;=.%])*)*"
val sampleUrl = "https://www.google.com"
val urlMatchers = Pattern.compile(urlRegex).matcher(sampleUrl)
assert(urlMatchers.find())
This pattern works really fine on all APIs above 21.
It seems the earlier versions do not support named groups. As per this source, the named groups were introduced in Kotlin 1.2. Remove them if you do not need those submatches and only use the regex for validation.
Your regex is very inefficient as it contains a lot of nested quantified groups. See a "cleaner" version of it below.
Also, it seems you want to check if there is a regex match inside your input string. Use Regex#containsMatchIn():
val urlRegex = "(?:(?:http|ftp)s?://)?[\\w:#.-]+\\.[\\w-]+(?::\\d+)?\\??[\\w.~:/?#\\[\\]#!$&'()*+,;=.%-]*"
val sampleUrl = "https://www.google.com"
val urlMatchers = Regex(urlRegex).containsMatchIn(sampleUrl)
println(urlMatchers) // => true
See the Kotlin demo and the regex demo.
If you need to check the whole string match use matches:
Regex(urlRegex).matches(sampleUrl)
See another Kotlin demo.
Note that to define a regex, you need to use the Regex class constructor.

extracting a particular field from url

I want to extract particular fields from a url of a facebookpage. Iam not able to extract since link format is not static.eg:if I gave the below examples as input it should give the o/p as what we desire
1)https://www.facebook.com/pages/Ice-cream/109301862430120?rf=102173023157556
o/p -109301862430120
What about this type of link
can anyone help me
So in short, you want to get name after last / and (if there is any) before ? mark.
You can do it with using URI and File classes like
String data = "https://www.facebook.com/pages/Anti-Christian-sentiment/149675731889496?ref=br_tf";
System.out.println(new File(new URI(data).getRawPath()).getName());
Output: 149675731889496
If you need to use regex then you can use
([^/?]+)(\\?|$)
and just read content of group 1 (the one in first pair of parenthesis).
If you don't want to use groups, and make regex match only digit part (without including ? in match) then you can use look around mechanisms like look-ahead (?=...). Regex you would have to use would look like
[^/?]+(?=\\?|$)
Code example:
String data = "https://www.facebook.com/pages/Anti-Christian-sentiment/149675731889496?ref=br_tf";
Pattern p = Pattern.compile("([^/?]+)(\\?|$)");
Matcher m = p.matcher(data);
if (m.find()){
System.out.println(m.group(1));
}
Output:
149675731889496

Give Parameter to Regex in Java

I try to parse log file:
'Del username /PART="deneme" /ROLE="VR_ANALYST" /TYPE="C" /CAPABILITY="S" /ADD' (S)
'Del Batu /PART="_PROJECT" /ROLE="VR_AUTHOR" /TYPE="R" /CAPABILITY="S" /ADD' (S)
RULE => 'Del input ........ /ROLE="input2" .......
input and input2 will given from user.
In this sentence :
username: should be a parameter (input from user)
VR_ANALYST: should be a parameter (input from user)
'Del: must be in the regex (the first four letters must be 'Del)
/ROLE="": must be in the regex
1)Regex should start with 'Del
2)continue with first input
3)some other strings
4)/ROLE="
5)second input
6)"
7)continue with other strings
I have nearly no knowledge about regex but I try to do :
'Del parameter \"*"\ (/ROLE=") parameter2 (") \*
Could you please give some advice how can create a regex of this sentence and use my paramters in this regex.
1.About regex i'll suggest You some of a online regex checker like (http://www.regexplanet.com/advanced/java/index.html) and just learn a little, its pretty simple ;)
2.If u want to add Your parameters to the regex u can use
replace(oldChar, newChar) on string that contains regex pattern.
Try this REGEX..
^'Del\s*parameter.*/ROLE="parameter2".*

match a string of characters between tags:

I have the following strings:
<PAUL SAINT-KARL 1997-05-07>
<BOB DEAN 2001-05-07>
<GUY JEDDY 2007-05-07>
I want a java regex that would match this type of pattern "name and date" and then extract the name and date separately.
I able to match them separately with the following java regex:
1) (\d{4}-\d{2}-\d{2})>
2) <([ A-Z&#;0-9-]*+)
What I'm looking for is one regex that would identify the full text pattern as provided, and then extract the subsections, such as the actual name, and the date.
I'm looking to use Matcher.group() to retrieve the complete match from the target string.
Thanks
Try this:
"<([ A-Z&#;0-9-]*?) (\\d{4}-\\d{2}-\\d{2})>"
I changed the *+ to *? to make the * match lazily.

How to split this string using Java Regular Expressions

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)?

Categories