Resteasy Path with expressions including spaces - regex

I am reading the book "RESTful Java"; now I am working with the examples from chapter 4.
I would like to change the expressions to accept names with spaces. I've changed the expressions to "[a-zA-Z ]+" but it didn't work. Is there a way to make this work?
Many thanks
#GET
#Path("{first : [a-zA-Z]+}-{last:[a-zA-Z]+}")
#Produces("application/xml")
public StreamingOutput getCustomerFirstLast(#PathParam("first") String first,
#PathParam("last") String last)
{
System.out.println(String.format("Parameters. First=%s; Last=%s", first, last));
Customer found = null;
for (Customer cust : customerDB.values())
{
if (cust.getFirstName().equals(first) && cust.getLastName().equals(last))
{
found = cust;
break;
}
}
if (found == null)
{
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
final Customer customer = found;
return new StreamingOutput()
{
public void write(OutputStream outputStream) throws IOException, WebApplicationException
{
outputCustomer(outputStream, customer);
}
};
}
Edit: I was not clear.
When I try the URL: /customers/Sylvie-Van%20der%20Vaart I am getting the following error:
HTTP ERROR 404
Problem accessing
/customers/Sylvie-Van%20der%20Vaart.
Reason:
Could not find resource for relative :
/customers/Sylvie-Van%20der%20Vaart of
full path:
http://localhost:9095/customers/Sylvie-Van%20der%20Vaart
I tried simply to add to the regular expression one space:#Path("{first : [a-zA-Z ]+}-{last:[a-zA-Z ]+}").

[a-zA-Z]+([\\s]?[a-zA-Z]+)*
[a-zA-Z]+ is for the first name
([\s]?[a-zA-Z]+)* is for the optional more names
I think above regular expression will handle the cases you are asking.

Related

How to Set Multple Regex Costraints on textbox in ZKOSS

I have a textbox which should only accept Characters:-for that first regex has been set in constraint and it should not accept some reserved keywords that are A,R,F,U .Since two different constraints are set ,i want user to see the specific message ,for first it should be Illegal Value i.e default zkoss error and when he/she enters a reserved character ,it should show that reserved code has been put.
But somehow the following code doesnt work :
field_code.setConstraint("/[a-zA-Z]/ : {Illegal Value} ,/[^AaRrUuFf]/ : Reserved Code");
The output is the first regex works fine but on offending the same " {Illegal Value} ,/[^AaRrUuFf]/ : Reserved Code" is displayed as error.
You can't do it in the zul, but with help of a SimpleConstraint you could create this.
Create your own class, and extend SimpleConstraint.
Then hold 2 Matcher vars for each constraint.
At last, override the Validate method to something like this :
#Override
public void validate(Component comp, Object value) {
if (value != null && value instanceof String) {
String stringValue = (String) value;
if (!expression1.reset(stringValue).matches()) {
throw new WrongValueException(comp, errorMsg1);
}
if (!expression2.reset(stringValue).matches()) {
throw new WrongValueException(comp,errorMsg2);
}
} else {
// do what needs to be done when value is null or not a String.
}
}

Using Regex Formatter To Verify Email

This is my code but it doesn't work,why?I use the RegexFormatter("#.*") but it seems doesn't work.it can't check the JFormattedTextField whether #.* contain or not.And I want to show the result at the verify label how should I do?
public class hw5 extends JFrame {
private JPanel contentPane;
private JPasswordField passwordField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
hw5 frame = new hw5();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public hw5() {
setTitle("hw5");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFormattedTextField FormattedField = new JFormattedTextField(new RegexFormatter("*#*.*"));
}
}
class RegexFormatter extends DefaultFormatter {
private Pattern pattern;
private Matcher matcher;
public RegexFormatter() {
super();
}
public Object stringToValue(String text) throws ParseException {
Pattern pattern = getPattern();
if (pattern != null) {
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
setMatcher(matcher);
return super.stringToValue(text);
}
throw new ParseException("Pattern did not match", 0);
}
return text;
}
}
Your regex *#*.* if wrong. It means:
One *
Followed by zero or more #
Followed by zero or more characters (any)
Validating an e-mail via regex is very complicated (if you want to do it correctly). Since it seems all you want to do is check for "something with an #", I'd suggest the following regex:
[^#]+#[^#]+
Or better yet:
^[^#]+#.[^#]+$
It means:
^: start of string
[^#]+: followed by one or more characters that are not #
#: a single #
[^#]+: followed by one or more characters that are not #
$
This will match a#b and alpha+beta$#^& but will fail on foo or a#b#c. Whether this is sufficient for you, I don't know. There are far better ways to validate whether an input is an e-mail address.

Finding Noun Phrases in sentiment analysis using stanford POS tagger

**I am making a project on sentiment analysis. so i used stanford POS tagger to tag the sentence. I want to extract noun phrases from the sentences but it was only tagging noun.
How do i get noun phrases from that. i code in java.
i searched on websites and i found this for making a noun phrase:
For noun phrases, this pattern or regular expression is the following:
(Adjective | Noun)* (Noun Preposition)? (Adjective | Noun)* Noun
i.e. Zero or more adjectives or nouns, followed by an option group of a noun and a preposition, followed again by zero or more adjectives or nouns, followed by a single noun.
i was trying to code it using java's reguler expression library. i.e regex. but couldnt find the desired result.
Does anyone has code for it?
**
I have coded this. and solution is..
it will extracy all the noun phrase from a sentence containing only noun.
for eg. like NP is: the white tiger. it will extract "white tiger".
public static void maketree(String sent, int sno, Sentences sen)
{
try
{
LexicalizedParser parser = LexicalizedParser.loadModel("stanford-parser-full-2014-01-04\\stanford-parser-3.3.1-models\\edu\\stanford\\nlp\\models\\lexparser\\englishPCFG.ser.gz");
String sent2 = "Picture Quality of this camera is very good";
String sent1[] = sent2.split(" ");
List<CoreLabel> rawWords = Sentence.toCoreLabelList(sent1);
Tree x = parser.apply(rawWords);
x.indexLeaves();
System.out.println(x);
findNP(x,sen);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void findNP(Tree t, Sentences sent)
{
if (t.label().value().equals("NP"))
{
noun(t,sent);
}
else
{
for (Tree child : t.children())
{
findNP(child,sent);
}
}
}
public static void noun(Tree t,Sentences sent)
{
String noun="";
for(Tree temp : t.children())
{
String val = temp.label().value();
if(val.equals("NN") || val.equals("NNS") || val.equals("NNP") || val.equals("NNPS"))
{
Tree nn[] = temp.children();
String ss = Sentence.listToString(nn[0].yield());
if(noun=="")
{
noun = ss;
}
else
{
noun = noun+" "+ss;
}
}
else
{
if(noun!="")
{
sent.nouns[i++] = noun;
noun = "";
}
noun(temp,sent);
}
}
if(noun!="")
{
sent.nouns[i++] = noun;
}
}
Could you please check the link and comment on this. Could you please me if
"the white tiger" would get the same result with your above code.probably the code is not complete and thats why I am getting some error.
for eg:
sent.nouns[i++] = noun; // sent.nouns????? it seems to be undefined. could you please get the complete code or if you can commnet on the below link.
here is the link
Extract Noun phrase using stanford NLP
Thanks for the help

How to combine multiple criteria in OR query dynamically in Play Morphia

I am trying to use a kind of builder pattern to build an OR query using multiple criteria depending upon the scenario. An example is
public class Stylist extends Model {
public String firstName;
public String lastName;
public String status;
...
}
I would like to search Stylist collection if the first name or last name matches a given string and also status matches another string. I am writing the query as follows:
MorphiaQuery query = Stylist.q();
if (some condition) {
query.or(query.criteria("status").equal("PendingApproval"), query.criteria("status").equal(EntityStatus.ACTIVE));
}
if (some other condition as well) {
query.or(query.criteria("firstName").containsIgnoreCase(name), query.criteria("lastName").containsIgnoreCase(name));
}
When both the conditions are met, I see that query contains only the criteria related to firstName and lastName i.e. different OR criteria are not added/appended but overwritten. It's quite different from filter criteria where all the different filter conditions are appended and you can easily build queries containing multiple AND conditions.
I can solve the problem by putting my conditions differently and building my queries differently but doesn't seem to be an elegant way. Am I doing something wrong ?
I am using Play! Framework 1.2.4 and Play Morphia module version 1.2.5a
Update
To put it more clearly, I would like to AND multiple OR queries. Concretely, in the above mentioned scenario, I would like to
I would like to search for Stylists where :
firstName or lastName contains supplied name AND
status equals ACTIVE or PENDING_APPROVAL.
I have been able to construct the query directly on Mongo shell through :
db.stylists.find({$and: [{$or : [{status: "PENDING_APPROVAL"}, {status : "ACTIVE"}]},{$or : [{firstName : { "$regex" : "test" , "$options" : "i"}}, {lastName : { "$regex" : "test" , "$options" : "i"}}]}] }).pretty();
But have not able to achieve the same through Query API methods. Here is my attempt :
Query<Stylist> query = MorphiaPlugin.ds().find(Stylist.class);
CriteriaContainer or3 = query.or(query.criteria("firstName").containsIgnoreCase(name), query.criteria("lastName").containsIgnoreCase(name));
CriteriaContainer or4 = query.or(query.criteria("status").equal("PENDING_APPROVAL"), query.criteria("status").equal("ACTIVE"));
query.and(or3, or4);
query.toString() results in following output : { "$or" : [ { "status" : "PENDING_APPROVAL"} , { "status" : "ACTIVE"}]}
Not sure, where am I missing ?
I guess there could be 2 ways to handle your case:
first, use List<Criteria>
MorphiaQuery query = Stylist.q();
List<Criteria> l = new ArrayList<Criteria>()
if (some condition) {
l.add(query.criteria("status").equals("PendingApproval");
l.add(query.criteria("status").equal(EntityStatus.ACTIVE));
}
if (some other conditional as well) {
l.add(query.criteria("firstName").containsIgnoreCase(name));
l.add(query.criteria("lastName").containsIgnoreCase(name));
}
query.or(l.toArray());
Second, use CritieriaContainer
MorphiaQuery query = Stylist.q();
CriteriaContainer cc = null;
if (some condition) {
cc = query.or(query.criteria("status").equal("PendingApproval"), query.criteria("status").equal(EntityStatus.ACTIVE));
}
if (some other condition) {
if (null != cc) query.or(cc, query.criteria("firstName").containsIgnoreCase(name), query.criteria("lastName").containsIgnoreCase(name));
else query.or(query.criteria("firstName").containsIgnoreCase(name), query.criteria("lastName").containsIgnoreCase(name));
}

How do I check if a filename matches a wildcard pattern

I've got a wildcard pattern, perhaps "*.txt" or "POS??.dat".
I also have list of filenames in memory that I need to compare to that pattern.
How would I do that, keeping in mind I need exactly the same semantics that IO.DirectoryInfo.GetFiles(pattern) uses.
EDIT: Blindly translating this into a regex will NOT work.
I have a complete answer in code for you that's 95% like FindFiles(string).
The 5% that isn't there is the short names/long names behavior in the second note on the MSDN documentation for this function.
If you would still like to get that behavior, you'll have to complete a computation of the short name of each string you have in the input array, and then add the long name to the collection of matches if either the long or short name matches the pattern.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FindFilesRegEx
{
class Program
{
static void Main(string[] args)
{
string[] names = { "hello.t", "HelLo.tx", "HeLLo.txt", "HeLLo.txtsjfhs", "HeLLo.tx.sdj", "hAlLo20984.txt" };
string[] matches;
matches = FindFilesEmulator("hello.tx", names);
matches = FindFilesEmulator("H*o*.???", names);
matches = FindFilesEmulator("hello.txt", names);
matches = FindFilesEmulator("lskfjd30", names);
}
public string[] FindFilesEmulator(string pattern, string[] names)
{
List<string> matches = new List<string>();
Regex regex = FindFilesPatternToRegex.Convert(pattern);
foreach (string s in names)
{
if (regex.IsMatch(s))
{
matches.Add(s);
}
}
return matches.ToArray();
}
internal static class FindFilesPatternToRegex
{
private static Regex HasQuestionMarkRegEx = new Regex(#"\?", RegexOptions.Compiled);
private static Regex IllegalCharactersRegex = new Regex("[" + #"\/:<>|" + "\"]", RegexOptions.Compiled);
private static Regex CatchExtentionRegex = new Regex(#"^\s*.+\.([^\.]+)\s*$", RegexOptions.Compiled);
private static string NonDotCharacters = #"[^.]*";
public static Regex Convert(string pattern)
{
if (pattern == null)
{
throw new ArgumentNullException();
}
pattern = pattern.Trim();
if (pattern.Length == 0)
{
throw new ArgumentException("Pattern is empty.");
}
if(IllegalCharactersRegex.IsMatch(pattern))
{
throw new ArgumentException("Pattern contains illegal characters.");
}
bool hasExtension = CatchExtentionRegex.IsMatch(pattern);
bool matchExact = false;
if (HasQuestionMarkRegEx.IsMatch(pattern))
{
matchExact = true;
}
else if(hasExtension)
{
matchExact = CatchExtentionRegex.Match(pattern).Groups[1].Length != 3;
}
string regexString = Regex.Escape(pattern);
regexString = "^" + Regex.Replace(regexString, #"\\\*", ".*");
regexString = Regex.Replace(regexString, #"\\\?", ".");
if(!matchExact && hasExtension)
{
regexString += NonDotCharacters;
}
regexString += "$";
Regex regex = new Regex(regexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return regex;
}
}
}
}
You can simply do this. You do not need regular expressions.
using Microsoft.VisualBasic.CompilerServices;
if (Operators.LikeString("pos123.txt", "pos?23.*", CompareMethod.Text))
{
Console.WriteLine("Filename matches pattern");
}
Or, in VB.Net,
If "pos123.txt" Like "pos?23.*" Then
Console.WriteLine("Filename matches pattern")
End If
In c# you could simulate this with an extension method. It wouldn't be exactly like VB Like, but it would be like...very cool.
You could translate the wildcards into a regular expression:
*.txt -> ^.+\.txt$
POS??.dat _> ^POS..\.dat$
Use the Regex.Escape method to escape the characters that are not wildcars into literal strings for the pattern (e.g. converting ".txt" to "\.txt").
The wildcard * translates into .+, and ? translates into .
Put ^ at the beginning of the pattern to match the beginning of the string, and $ at the end to match the end of the string.
Now you can use the Regex.IsMatch method to check if a file name matches the pattern.
Just call the Windows API function PathMatchSpecExW().
[Flags]
public enum MatchPatternFlags : uint
{
Normal = 0x00000000, // PMSF_NORMAL
Multiple = 0x00000001, // PMSF_MULTIPLE
DontStripSpaces = 0x00010000 // PMSF_DONT_STRIP_SPACES
}
class FileName
{
[DllImport("Shlwapi.dll", SetLastError = false)]
static extern int PathMatchSpecExW([MarshalAs(UnmanagedType.LPWStr)] string file,
[MarshalAs(UnmanagedType.LPWStr)] string spec,
MatchPatternFlags flags);
/*******************************************************************************
* Function: MatchPattern
*
* Description: Matches a file name against one or more file name patterns.
*
* Arguments: file - File name to check
* spec - Name pattern(s) to search foe
* flags - Flags to modify search condition (MatchPatternFlags)
*
* Return value: Returns true if name matches the pattern.
*******************************************************************************/
public static bool MatchPattern(string file, string spec, MatchPatternFlags flags)
{
if (String.IsNullOrEmpty(file))
return false;
if (String.IsNullOrEmpty(spec))
return true;
int result = PathMatchSpecExW(file, spec, flags);
return (result == 0);
}
}
Some kind of regex/glob is the way to go, but there are some subtleties; your question indicates you want identical semantics to IO.DirectoryInfo.GetFiles. That could be a challenge, because of the special cases involving 8.3 vs. long file names and the like. The whole story is on MSDN.
If you don't need an exact behavioral match, there are a couple of good SO questions:
glob pattern matching in .NET
How to implement glob in C#
For anyone who comes across this question now that it is years later, I found over at the MSDN social boards that the GetFiles() method will accept * and ? wildcard characters in the searchPattern parameter. (At least in .Net 3.5, 4.0, and 4.5)
Directory.GetFiles(string path, string searchPattern)
http://msdn.microsoft.com/en-us/library/wz42302f.aspx
Plz try the below code.
static void Main(string[] args)
{
string _wildCardPattern = "*.txt";
List<string> _fileNames = new List<string>();
_fileNames.Add("text_file.txt");
_fileNames.Add("csv_file.csv");
Console.WriteLine("\nFilenames that matches [{0}] pattern are : ", _wildCardPattern);
foreach (string _fileName in _fileNames)
{
CustomWildCardPattern _patetrn = new CustomWildCardPattern(_wildCardPattern);
if (_patetrn.IsMatch(_fileName))
{
Console.WriteLine("{0}", _fileName);
}
}
}
public class CustomWildCardPattern : Regex
{
public CustomWildCardPattern(string wildCardPattern)
: base(WildcardPatternToRegex(wildCardPattern))
{
}
public CustomWildCardPattern(string wildcardPattern, RegexOptions regexOptions)
: base(WildcardPatternToRegex(wildcardPattern), regexOptions)
{
}
private static string WildcardPatternToRegex(string wildcardPattern)
{
string patternWithWildcards = "^" + Regex.Escape(wildcardPattern).Replace("\\*", ".*");
patternWithWildcards = patternWithWildcards.Replace("\\?", ".") + "$";
return patternWithWildcards;
}
}
For searching against a specific pattern, it might be worth using File Globbing which allows you to use search patterns like you would in a .gitignore file.
See here: https://learn.microsoft.com/en-us/dotnet/core/extensions/file-globbing
This allows you to add both inclusions & exclusions to your search.
Please see below the example code snippet from the Microsoft Source above:
Matcher matcher = new Matcher();
matcher.AddIncludePatterns(new[] { "*.txt" });
IEnumerable<string> matchingFiles = matcher.GetResultsInFullPath(filepath);
The use of RegexOptions.IgnoreCase will fix it.
public class WildcardPattern : Regex {
public WildcardPattern(string wildCardPattern)
: base(ConvertPatternToRegex(wildCardPattern), RegexOptions.IgnoreCase) {
}
public WildcardPattern(string wildcardPattern, RegexOptions regexOptions)
: base(ConvertPatternToRegex(wildcardPattern), regexOptions) {
}
private static string ConvertPatternToRegex(string wildcardPattern) {
string patternWithWildcards = Regex.Escape(wildcardPattern).Replace("\\*", ".*");
patternWithWildcards = string.Concat("^", patternWithWildcards.Replace("\\?", "."), "$");
return patternWithWildcards;
}
}