I am not good with regular expression patterns.
I have to put a validation on an string, to allow
only alphabets, numbers, decimals, spaces, comma and underscore
for allowing the alphabets and spaces I have /^[a-zA-Z][a-zA-Z\\s]+$/
Please help me in creating all the above conditions in one pattern.
Thanks
this regex should work for your requirements
'[a-zA-Z0-9_. ,]*'
In the regex, I specified the range a to z, A to Z (uppercase), 0 to 9 and the single character _, decimal point ".", space and a comma.
If you want to make sure you want at least one character after the first letter, you can replace the * with a +, or {2,} with at least 2 more characters, or {2,5} with between 2 and 5 characters.
You can try:
/^[\w., ]+$/
I don't know what are the requirements for the starting char, if there are any.
Rahul's answer gave me the direction to think, but for the visitors, may be this too can be helpfull
patternForClasName = /^([a-zA-Z0-9 _]+\.)*[a-zA-Z0-9 _]+$/;
// Allowing valid className which has a format abcsasa.dsd.dsd(the class or a package name can have an underscore or a numerical)
patternForName = /^([a-zA-Z0-9 _-]+)$/;
// Allowing alphanumeric + spaces + (_)underscore and a (-)dash
patternForDescription = /^([a-zA-Z0-9 _-]+[\,\.]+)*[a-zA-Z0-9 _-]*$/;
// Allowing alphanumeric,spaces, (_)underscore, (-)dash, comma, decimal
patternURLFormat = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
// For a valid URL
Related
I know there are already some kind of posts, that try to explain the RegEx-string. but i still don't get it. In my case, I need a regex for a WPF, that only allows "Numeric-Keyboard". Its here in the Code:
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[-+]?[0-9]*,?[0-9]*");
e.Handled = regex.IsMatch(e.Text);
}
so here are some example-numbers, i need to allow:
"1" or "-1" or "-0,5" or "4,00" or "-3,56" or "3,3" or
" '-2, ' as '-2,0' or '-2' "
(so its all between -4 to +4. There can be a comma, But it don't have to be. If there s a comma, it needs one or 2 digits behind - not more. It should also be a "," not a "." - this is important)
Does anybody know how to write this RegEx-String? thanks
Breaking it down, what you are after is not that complicated.
First off, your maximum/minimum range is from -4 up till 4. Taking into consideration the decimal section, you can have the following: ^[+-]?4(,0{1,2})?$. So in here, we expect a + or a - (optionally), the number 4, optionally followed by a comma and one or two 0's.
In your case, we now need to match the middle of your range, that is, from -3.99 up till 3.99. This can be achieved as follows: ^[+-]?[0-3](,\d{1,2})?$. In this case, we are also expecting a + or a - (optionally). We then expect to match a digit, between 0 and 3, optionally followed by a comma and 1 or 2 digits.
Combining them, we end up with something like so: ^[+-]?((4(,0{1,2})?)|([0-3](,\d{1,2})?))$. Example available here.
EDIT:
As per the comments, you need to escape the slash in front of the \d, because the C# compiler will try and find a special meaning for \d, just like it does when you do \n, or \t. The easiest way is to use the # character, so that the C# compiler threats the string as a literal: Regex regex = new Regex(#"^[+-]?((4(,0{1,2})?)|([0-3](,\d{1,2})?))$");.
There are a number of online sites for testing regular expressions, that will break down the match string and provide an explanation for each element, e.g. https://regex101.com/
In your case, you need
optional '+' or '-'
either
a group consisting of
'4'
optionally followed by a group consisting of
',' and one or two '0'
or
a group consisting of
one character from '0' .. '3'
optionally followed by a group consisting of
',' and one or two characters from '0' to '9'
[+-]?(?:(?:4(?:,0{1,2})?)|(?:[0-3](?:,[0-9]{1,2})?))
string s = "-3,5;10;8.5;0;2;3.5;1,5";
string pattern = #"^-?[0-4](,\d{1,2})?$";
foreach(var num in s.Split(";"))
{
Console.WriteLine($"Num: {num}, Matches: {Regex.IsMatch(num, pattern)}");
}
I need to enter amount in a textbox which allows numbers with decimal point and commas.
What is the regular expression for this?
I used the below
txtInitialAmountGuarDetails.ValidationSettings.RegularExpression.ValidationExpression
= #"^[-+]?\d*[0-9](|.\d*[0-9])(|,\d*[0-9])?$";
But it not working for large numbers like 300,000,000,000,000.
Build it up piecemeal. Given a US locale, a number with these rules has in order:
The string beginning: ^
An optional sign: [+-]?
Up to 3 digits: \d{1,3}
A comma followed by 3 digits, repeated any number of times: (?:,\d{3})*
An optional decimal point and decimal part: (?:[.]\d+)?
The string end: $
Do you have restrictions on the number of digits after the decimal point? Then change the last plus sign to {2} for 2 digits.
So, the regex is:
#"^[+-]?\d{1,3}(?:,\d{3})*(?:[.]\d+)?$"
Or, if you want to explain your work, use the x option and:
#"(?x) # Extended format.
^[+-]? # Optional sign.
\d{1,3} # Initial 1-3 digits.
(?:,\d{3})* # Any number of commas followed by 3 digits.
(?:[.]\d+)?$" # An optional decimal point followed by any number of digits.
But does C# have a locale-dependent validator already?
I have not run it, but you can try it out.
var regexp =/^\s*?([\d\,]+(\.\d{1,2})?|\.\d{1,2})\s*$/;
This works: \d{1,3}(,\d{3})*\.{0,1}(\d{3},)*\d{0,3}
As for the after the comma issue, any choice should be fine. If you go with commas, my regex works. If you do 5 digits then a space just replace the end with (\d{5}\s{1})*\d{0,5}. And ofcourse if you just dont use any deliminator after the decimal you just put \d*
You can try this regex too:
^([+-]?\d{1,3}(?:,\d{1,3})*(?:\.\d+)*)$
Keep in mind . has a specific meaning in regex engine so it is necessary to escape it.
I would also suggest you to not use regex for this task instead look at masked textbox.
try this one:
^([0-9]{3}[,.]|)+[0-9]{0,3}$
let me know if it needs any enhancements...
My Regex is removing all numeric (0-9) in my string.
I don't get why all numbers are replaced by _
EDIT: I understand that my "_" regex pattern changes the characters into underscores. But not why numbers!
Can anyone help me out? I only need to remove like all special characters.
See regex here:
string symbolPattern = "[!##$%^&*()-=+`~{}'|]";
Regex.Replace("input here 12341234" , symbolPattern, "_");
Output: "input here ________"
The problem is your pattern uses a dash in the middle, which acts as a range of the ascii characters from ) to =. Here's a breakdown:
): 41
1: 49
=: 61
As you can see, numbers start at 49, and falls between the range of 41-61, so they're matched and replaced.
You need to place the - at either the beginning or end of the character class for it to be matched literally rather than act as a range:
"[-!##$%^&*()=+`~{}'|]"
you must escape - because sequence [)-=] contains digits
string symbolPattern = "[!##$%^&*()\-=+`~{}'|]";
Move the - to the end of the list so it is seen as a literal:
"[!##$%^&*()=+`~{}'|-]"
Or, to the front:
"[-!##$%^&*()=+`~{}'|]"
As it stands, it will match all characters in the range )-=, which includes all numerals.
You need to escape your special characters in your regex. For instance, * is a wildcard match. Look at what some of those special characters mean for your match.
I've not used C#, but typically the "*" character is also a control character that would need escaping.
The following matches a whole line of any characters, although the "^" and "$" are some what redundant:
^.*$
This matches any number of "A" characters that appear in a string:
A*
The "Owl" book from oreilly is what you really need to research this:
http://shop.oreilly.com/product/9780596528126.do?green=B5B9A1A7-B828-5E41-9D38-70AF661901B8&intcmp=af-mybuy-9780596528126.IP
I know this stuff has been talked about a lot, but I'm having a problem trying to match the following...
Example input: "test test 310-315"
I need a regex expression that recognizes a number followed by a dash, and returns 310. How do I include the dash in the regex expression though. So the final match result would be: "310".
Thanks a lot - kcross
EDIT: Also, how would I do the same thing but with the dash preceding, but also take into account that the number following the dash could be a negative number... didnt think of this one when I wrote the question immediately. for example: "test test 310--315" returns -315 and "test 310-315" returns 315.
Regex regex = new Regex(#"\d+(?=\-)");
\d+ - Looks for one or more digits
(?=\-) - Makes sure it is followed by a dash
The # just eliminates the need to escape the backslashes to keep the compiler happy.
Also, you may want this instead:
\d+(?=\-\d+)
This will check for a one or more numbers, followed by a dash, followed by one or more numbers, but only match the first set.
In response to your comment, here's a regex that will check for a number following a -, while accounting for potential negative (-) numbers:
Regex regex = new Regex(#"(?<=\-)\-?\d+");
(?<=\-) - Negative lookbehind which will check and make sure there is a preceding -
\-? - Checks for either zero or one dashes
\d+ - One or more digits
(?'number'\d+)- will work ( no need to escape ). In this example the group containing the single number is the named group 'number'.
if you want to match both groups with optional sign try:
#"(?'first'-?\d+)-(?'second'-?\d+)"
See it working here.
Just to describe, nothing complicated, just using -? to match an optional - and \d+ to match one or more digit. a literal - match itself.
here's some documentation that I use:
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
in the comments section of that page, it suggests escaping the dash with '\-'
make sure you escape your escape character \
You would escape the special meaning of - in regex language (means range) using a backslash (\). Since backslash has a special meaning in C# literals to escape quotes or be part of some characters, you need to escape that with another backslash(\). So essentially it would be \d+\\-.
\b\d*(?=\-) you will want to look ahead for the dash
\b = is start at a word boundry
\d = match any decimal digit
* = match the previous as many times as needed
(?=\-) = look ahead for the dash
Edited for Formatting issue with the slash not showing after posting
I want to check in a C# program, if a user input is a single word. The word my only have characters A-Z and a-z. No spaces or other characters.
I try [A-Za-z]* , but this doesn't work. What is wrong with this expression?
Regex regex = new Regex("[A-Za-z]*");
if (!regex.IsMatch(userinput);)
{
...
}
Can you recomend website with a comprensiv list of regex examples?!
It probably works, but you aren't anchoring the regular expression. You need to use ^ and $ to anchor the expression to the beginning and end of the string, respectively:
Regex regex = new Regex("^[A-Za-z]+$");
I've also changed * to + because * will match 0 or more times while + will match 1 or more times.
You should add anchors for start and end of string: ^[A-Za-z]+$
Regarding the question of regex examples have a look at http://regexlib.com/.
For the regex, have a look at the special characters ^ and $, which represent starting and ending of string. This site can come in handy when constructing regexes in the future.
The asterisk character in regex specifies "zero or more of the preceding character class".
This explains why your expression is failing, because it will succeed if the string contains zero or more letters.
What you probably intended was to have one or more letters, in which case you should use the plus sign instead of the asterisk.
Having made that change, now it will fail if you enter a string that doesn't contain any letters, as you intended.
However, this still won't work for you entirely, because it will allow other characters in the string. If you want to restrict it to only letters, and nothing else, then you need to provide the start and end anchors (^ and $) in your regex to make the expression check that the 'one or more letters' is attached to the start and end of the string.
^[a-zA-Z]+$
This should work as intended.
Hope that helps.
For more information on regex, I recommend http://www.regular-expressions.info/reference.html as a good reference site.
I don't know what the C#'s regex syntax is, but try [A-Za-z]+.
Try ^[A-Za-z]+$ If you don't include the ^$ it will match on any part of the string that has a alpha characters in it.
I know the question is only about strictly alphabetic input, but here's an interesting way of solving this which does not break on accented letters and other such special characters.
The regex "^\b.+?\b" will match the first word on the start of a string, but only if the string actually starts with a valid word character. Using that, you can simply check if A) the string matches, and B) the length of the matched string equals your full string's length:
public Boolean IsSingleWord(String userInput)
{
Regex firstWordRegex = new Regex("^\\b.+?\\b");
Match firstWordMatch = firstWordRegex.Match(userInput);
return firstWordMatch.Success && firstWordMatch.Length == userInput.Length;
}
The other persons have wrote how to resolve the problem you know. Now I'll speak about the problem you perhaps don't know: diacritics :-) Your solution doesn't support àèéìòù and many other letters. A correct solution would be:
^(\p{L}\p{M}*)+$
where \p{L} is any letter plus \p{M}* that is 0 or more diacritic marks (in unicode diacritics can be "separated" from base letters, so you can have something like a + ` = à or you can have precomposed characters like the standard à)
if you just need the characters a-zA-Z you could simply iterate over the characters and compare the single characters if they are inside your range
for example:
for each character c: ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
This could increase your performance