How to set a RegExp to have a real matching judgement? - regex

I would like to set a RegExp to have a matching judgement with String. I tried to use pattern.test(str), but if pattern is a part of string it will be true. It isn't what i want.
For example, I set my pattern is "/[a-z]/" and str is "abc123", it will be true by pattern.test(str). My prefer result is false, because the str contains "123", not every character is a-z. How can I do that? Thank you!
package {
import flash.display.Sprite;
public class regexp extends Sprite{
var pattern:RegExp=/[a-z]/;
var str:String="abc123";
public function regexp() {
trace(pattern.test(str));
}
}
}

Try this one:
var pattern:RegExp=/^[a-z]+?$/;

Related

Performance of the RegExp object

In the following code, the
I'd like to improve the performance by putting the RegExp object somewhere, but I can't figure out how to do the nest.
#ValidatorConstraint()
export class RegExp implements ValidatorConstraintInterface {
validate(kana: string, args: ValidationArguments) {
const str = new RegExp(/^[ァ-ヶー]+$/)
return str.test(kana)
}
defaultMessage(args: ValidationArguments) {
return 'Text should be'
}
}
thanks
If you need regexp only - simply use a built-in Matches validator:
#Matches(/^[ァ-ヶー]+$/)
public field: string;
In this case it will reuse regexp on every validation.
I thought of it this way.
const regexp = new RegExp(/^[ァ-ヶー]+$/)
#ValidatorConstraint()
export class RegExp implements ValidatorConstraintInterface {
validate(kana: string, args: ValidationArguments) {
return regexp.test(kana)
}
defaultMessage(args: ValidationArguments) {
return 'Text should be'
}
}

Swift extract string from string

I have a string that looks like:
"OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
But I need to get the sessionId that is in that string. Can someone help me in swift? I've tried regex but can't get it to work.
If you want to use Regular Expression you can use the following fucntion to match any occurrence of the pattern:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = NSRegularExpression(pattern: regex, options: nil, error: nil)!
let nsString = text as NSString
let results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
return map(results) { nsString.substringWithRange($0.range)}
}
And you can test it with the following regex :
let myStringToBeMatched = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
var results = self.matchesForRegexInText("(?<=sessionId=')(.*)(?=',)", text: myStringToBeMatched)
for item in results {
println(item)
}
The output should be :
big_super-long-id_string
Notes:
(?<=sessionId=') means preceded by sessionId='
(.*) means any character zero or more times
(?=',) means followed by ',
You can read more about Regex patterns here
I hope this help you.
let input = "OS-MF sessionId='big_super-long-id_string', factor='PASSCODE'"
let sessionID = input.componentsSeparatedByString("sessionId='").last!.componentsSeparatedByString("',").first!
println(sessionID) // "big_super-long-id_string"

Character Class \w not Working?

I'm doing the following regular expression in Node:
var checkPath = '^\/path\/([\w]+)\/messages$';
var path = '/path/54946fde030ba8cc5471efc9/messages';
var match = path.match(checkPath);
This doesn't seem to work.
However, when I do this:
var checkPath = '^\/path\/([0-9a-z]+)\/messages$';
var path = '/path/54946fde030ba8cc5471efc9/messages';
var match = path.match(checkPath);
It seems to work.
What is the difference?
You may want to write like
var checkPath = '^/path/(\\w+)/messages$';
var path = '/path/54946fde030ba8cc5471efc9/messages';
var match = path.match(checkPath);
Changes made
Escape \w as \\w
\w => [a-zA-Z0-9_] hence enclosing \w in another class does not add any advantage, written simply as \w

How do I create a regex to remove underscore

I am using MVC 3 with Razor. I can't figure out how to code a string extension regex to take this:
This_is_some_text
to display:
This is some text
I set up some enums for a drop down list, so they appear thusly (obviously I can't create an enum with a space):
public enum MyProperty
{
This_is_some_text,
This_is_some_other_text
}
I just cannot figure out the regex is to do what I want if I am doing this:
public static string EnumToDisplay(this string str)
{
return Regex.Replace(str, "[What is the regex I should use?]");
}
As a bonus for me I would also like to add a period "." to the end of the enum. The reason for this is that I have OCD and my enums are taking the form of short sentences. :)
Thanks!
Why not use String.Replace() for this? RegEx seems a bit overkill.
public static string EnumToDisplay(this string str)
{
return str.Replace('_', ' ') + ".";
}
Why do you want to use regular expressions? A very wise man once said, I quote:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
How about using the [Display] attribute which is kinda designed exactly for this purpose:
public enum MyProperty
{
[Display(Name = "This is some super text")]
This_is_some_text,
[Display(Name = "And this is some other text")]
This_is_some_other_text
}
and then writing a custom Html helper:
public static class HtmlExtensions
{
public static IHtmlString DisplayForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
if (!typeof(TProperty).IsEnum)
{
throw new ArgumentException("sorry this helper is inteded to be used with enum types");
}
var model = htmlHelper.ViewData.Model;
if (htmlHelper.ViewData.Model == null)
{
return MvcHtmlString.Empty;
}
var field = typeof(TProperty).GetField(expression.Compile()(htmlHelper.ViewData.Model).ToString());
if (field == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
var display = field.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute;
if (display == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
return new HtmlString(htmlHelper.Encode(display.Name));
}
}
So now assuming you have a view model:
public class MyViewModel
{
public MyProperty Foo { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = MyProperty.This_is_some_other_text
};
return View(model);
}
}
you could use the custom helper we just wrote in the view to display a user friendly text that we might have associated to an ugly enum. Hey, now you could even have this working with globalization and multiple languages using resources:
#model MyViewModel
#Html.DisplayForEnum(x => x.Foo)
I do not know about asp.net - but there should be a really simple method that replaces one character with another char. Like:
String.replace( myString, '_',' ' );
You can use the replacement pattern which is also called substitution.
You can find graet info here:
http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx
Good luck

RegularExpressionAttribute - How to make it not case sensitive for client side validation?

I have a string that I use for client side validation:
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";
I use this string in my [RegularExpression(regex, ErrorMessage = "invalid")] attribute.
I know that the /i flag for a Javascript regex is used to make it case insensitive, but just tacking it on to the end of my regex (i.e. #"^....$/i" isn't working - the regex validation fails completely, regardless of what is entered (valid or not).
What am I missing?
I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.
[RegularExpressionWithOptions(#".+#example\.com", RegexOptions = RegexOptions.IgnoreCase)]
C#
public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }
public RegexOptions RegexOptions { get; set; }
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value as string))
return true;
return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "regexwithoptions"
};
rule.ValidationParameters["pattern"] = Pattern;
string flags = "";
if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
flags += "m";
if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
flags += "i";
rule.ValidationParameters["flags"] = flags;
yield return rule;
}
}
JavaScript
(function ($) {
$.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
options.messages['regexwithoptions'] = options.message;
options.rules['regexwithoptions'] = options.params;
});
$.validator.addMethod("regexwithoptions", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
var reg = new RegExp(params.pattern, params.flags);
match = reg.exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
})(jQuery);
This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators
In C# you can inline some regex options. To specify the option to ignore case you would add (?i) to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator I doubt it; the regex should be vanilla enough to work for both engines.
In any case if it was valid it would look like this:
#"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";