Regex to match a doubles separated by one space only - c#

I am trying to check a match as the user enters values in the text box.
Valid values for the textbox are like this:
"-"
"-5.5"
"-5.5 6.5 7.5"
Invalid would be
"-5.5 6.5 "
Edit: ^there is more than one space between -5.5 and 6.5, but it doesn't show for some reason.
"3.5 "
^(-?)(\d+\.?\d?)\s?(-?\d+\.?\d?)
Keep in mind that the negative sign is the only special character, other than the decimal point, allowed in here.
Thanks.

You can use this:
^-(?:\d+[.]\d+(?:[ ]\d+[.]\d+)*)?$
Explanation:
^
- // Match '-'
(?: // An optional non-capturing group
\d+[.]\d+ // Match pattern - 14.45
(?: // A 0 or more times repeating Non-capture group
[ ] // A space
\d+[.]\d+ // Pattern matching - 14.56
)*
)?
$

I think this is what you're looking for:
^(-|-?\d+\.?\d?([ ]-?\d+\.?\d?)*)$
This will match either a single hyphen or any number of space-separated positive or negative numbers with an optional decimal point and at most one digit after it. This will allow values like "5.5 6.5" or "-5.5 -6.5" (your question didn't specify if it should match those or not)
You can test it here.
Update
This will allow many more matches, but satisfies the new requirement of supporting every valid sequence as the user is typing. Of course, it allows even more, since it's impossible to determine the difference between invalid input and input which is merely incomplete (e.g. -5 -).
^(-?(\d+\.?\d?( |$)|$))*$
You can test it here.

You can try this:
^(-(\d+\.\d+)*([ ]\d+\.\d+)*)$

Related

Regex match a string that is not part of a larger word [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 3 years ago.
I'm stumped on how to even go about this.
I am trying to match the string "ashi" but not if the word containing it is in a small list of known false positives like "flashing", "lashing", "smashing". The false positive words can appear in the string as well as long as the string "ashi" (not as part of one of the false positive words) is in the string it should return true.
I'm using C# and I was trying to go about it without using regular expressions, but I am having no luck.
These strings should return true
...somethingashisomething...
...something2!ashi*&something...
... something ashi something flashing...
These strings should return false
...somethingflashingsomething...
...smashingthesomething...
...the lashings are too tight...
Another option might be to use a negative lookbehind with a nested lookahead to match words that start with fl but not if they are followed by ashing to match ashi but not flashing.
(?<!\bfl(?=ashing\b))ashi
Explanation
(?<! Negative lookbehind, assert what is directly on the right is not
\bfl Word boundary, match fb
(?= Positive lookahead, assert what is directly on the right is
ashing\b Match ashing and word boundary
) Close positive lookahead
) Close positive lookbehind.
ashi Match literally
.NET Regex demo
Update
If you want to match and not match the updated values, you could use an alternation (?:sm|f?l) in the negative lookbehind to match sm or an optional f followed by l
(?<!(?:sm|f?l)(?=ashing))ashi
.NET regex demo | C# demo
You can make use of a capturing group:
(flashing)|ashi
If the first group is not empty, you matched flashing literally
The following will match ashi but not within flashing. I interpreted "word" loosely, so flashing is not required to be isolated as a separate word with space/punctuation delimiters.
(?<=(?<prefix>fl)|)ashi(?(prefix)(?!ng))
It is sufficient to return true/false over the entire pattern and won't require checking specific capture groups. In other words, it is usable with Regex.IsMatch().
Pattern details:
(?<= # Zero-width positive lookbehind: match but don't consume characters
(?<prefix>fl) # Named capture group to match "fl" at start of "flashing"
| # Alternate blank capture - will succeed if "fl" is not present
) # End lookbehind
ashi # match literal "ashi"
(?(prefix) # Conditional: Only match if named group prefix has successful capture (i.e. "fl" was matched)
(?!ng) # Zero-width negative loohahead: Fail match if "ng" follows
) # Close conditional (there is no false part, so match succeeds if "fl" was not present)
If flashing is only excluded as an isolated word, just add word boundary operators. This will match something like flashingwithnospace, whereas the first pattern would fail on that string:
(?<=(?<prefix>\bfl)|)ashi(?(prefix)(?!ng\b))
(FYI, the pattern will work in isolation, but if it is combined within another pattern, especially inside a repeating construction, it may not work due to the conditional on the named capture group. Once the named capture group has succeeded, the conditional will remain true while matching the larger pattern, even if it were to encounter another occurrence of ashi.)
The question gives the examples
...somethingashisomething...
...something2!ashi*&something...
... something ashi something...
The second and third examples can be found by including the word boundary \b in the search, i.e. search for \bashi\b. Finding the first example requires more knowledge of what the two enclosing somethings are. If they are alphanumeric then you need to specify the problem in much more detail.

Regular Expressions C#

I know there are many questions about making regular expressions, but they all seem to be about a single problem than the general usage. I, too, have a problem like to solve. I have tried to learn by reading about regular expressions, but it gets tricky quick. Here's my question:
C#
I need to validate two textboxes that exist on the same form. The math operations I've coded can handle any floating point number. For this particular application I know of three formats the numbers will be in or there is a mistake on the users behalf. I'd like to prevent those mistakes in example if an extra number is accidentally typed or if enter is hit too early, etc.
Here are the formats: "#.####" "##.####" "###.##" where the "#" represents a mandatory digit. The formats starting with a one or two digit whole number must have 4 trailing digits or more. I've capped it at 8, or so I tried to lol.The format starting with a three digit whole number should never be allowed to have more than two digits trailing the decimal.
Here's what I have tried thus far.
Regex acceptedInputRegex = new Regex(#"^\b[0-9]{3}.[0-9]{2}|[0-9]{1,2}.[0-9]{4,8}$");
Regex acceptedInputRegex = new Regex(#"^\b\d{3}.\d{2} | \d{1,2}.\d{4,8}$");
I have tried it in thinking a match was what I wanted to achieve and as if a match to my negated expression means there is a problem. I was unsuccessful in both attempts. This is the code:
if (acceptedInputRegex.IsMatch(txtMyTextBox1.Text) || acceptedInputRegex.IsMatch(txtMyTextBox2.Text))
{
} else
{
MessageBox.Show("Numbers are not in the right format", "Invalid Input!");
return;
}
Are regular expressions what I should be using to solve this problem?
If not, please tell me what you recommend. If so, please help me correct my regex.
Thanks.
You are close, you need to escape the dots and group the alternatives so that the ^ and $ anchors could be applied to both of them:
#"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$"
See the regex demo.
Details:
^ - start of string
(?: - start of a non-capturing group matching either of the two alternatives:
\d{3}\.\d{2} - 3 digits, . and 2 digits
| - or
\d{1,2}\.\d{4,8} - 1 or 2 digits, ., 4 to 8 digits
) - end of the non-capturing group
$ - end of string.
To make \d match only ASCII digits, use RegexOptions.ECMAScript option:
var isValid = Regex.IsMatch(s, #"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$", RegexOptions.ECMAScript);

Regex to match more than one word

I have an ASP.NET MVC application containing a form field called 'First/last name'. I need to add some basic validation to ensure people enter at least two words. It doesn't need to be totally comprehensive in checking word length etc, we essentially just need to prevent people from entering just their first name which is what's happening currently. I don't want to limit to just alphabetic characters as some names include punctuation. I just want to ensure that people have entered at least two words separated by a space.
I have the following regex currently:
[RegularExpression(#"^((\b[a-zA-Z]{2,40}\b)\s*){2,}$", ErrorMessage = "Invalid first/last name")]
This works to an extent (it checks for 2 words) but it's invalid if punctuation is entered, which isn't what I'm looking for.
Could anyone suggest how to modify the above so that it doesn't matter if punctuation is used in the words? I'm not good with the regular expression syntax, hence asking here.
Thanks.
You want two words, so at least one space between them, and beyond that you want to allow everything else (e.g., punctuation). So keep it simple:
\w.*\s.*\w
Or if you must anchor it to start and end:
^.*\w.*\s.*\w.*$
These will match, for example, D' Addario (but not D'Artagnan by itself, since it counts as one word by the space criterion).
Maybe just:
#"\w\s\w"
word white space word
Hi you can use this regex for validation
'^[a-zA-Z0-9]+ {1}[a-zA-Z0-9]+$`'
Demo http://rubular.com/r/YN8eFa1yFE
If you just want to allow a sequence of non-whitespace characters followed by 1 or more sequences of whitespace characters followed by non-whitespace characters, you can use
^\s*\S+(?:\s+\S+)+\s*$
See regex demo
It won't accept just First or First .
Regex breakdown:
^ - start of string
\s* - zero or more whitespace
\S+ - 1 or more non-whitespace symbols
(?:\s+\S+)+ - 1 or more sequences of ...
\s+ - 1 or more whitespace sequences (remove + to allow only 1 whitespace between words)
\S+ - 1 or more non-whitespace symbols
\s* - zero or more whitespace
$ - end of string

Validating Positive number with comma and period

I need a regular expression validation expression that will
ALLOW
positive number(0-9)
, and .
DISALLOW
letter(a-z)
any other letter or symbol except . and ,
for example, on my asp.net text box, if I type anything#!#--, the regular expression validation will disallow it, if I type 10.000,50 or 10,000.50 it should allowed.
I've been trying to use this regex:
^\d+(\.\d\d)?$
but my textbox also must allow , symbol and I tried using only integer regex validation, it did disallow if I type string, but it also disallow . and , symbol while it should allow number(0-9) and also . and , symbol
Don't Use \d to match [0-9] in .NET
First off, in .NET, \d will match any digits in any script, such as:
654۳۲١८৮੪૯୫୬१७੩௮௫౫೮൬൪๘໒໕២៧៦᠖
So you really want to be using [0-9]
Incomplete Spec
You say you want to only allow "digits, commas and periods", but I don't think that's the whole spec. That would be ^[0-9,.]+$, and that would match
...,,,
See demo.
Tweaking the Spec
It's hard to guess what you really want to allow: would 10,1,1,1 be acceptable?
We could start with something like this, to get some fairly well-formed strings:
^(?:[0-9]+(?:[.,][0-9]+)?|[1-9][0-9]{0,2}(?:(?:\.[0-9]{3})*|(?:,[0-9]{3})*)(?:\.[0-9]+)?)$
Play with the demo, see what should and shouldn't match... When you are sure about the final spec, we can tweak the regex.
Sample Matches:
0
12
12.123
12,12
12,123,123
12,123,123.12456
12.125.457.22
Sample Non-Matches:
12,
123.
1,1,1,1
Your regex would be,
(?:\d|[,\.])+
OR
^(?:\d|[,\.])+$
It matches one or more numbers or , or . one or more times.
DEMO
Maybe you can use this one (starts with digit, ends with digit):
(\d+[\,\.])*\d+
If you need more sophisticated price Regex you should use:
(?:(?:[1-9]\d?\d?([ \,\.]?\d{3})*)|0)(?:[\.\,]\d+)?
Edit: To make it more reliable (and dont get 00.50) you can add starting and ending symbol check:
(^|\s)(?:(?:[1-9]\d?\d?([ \,\.]?\d{3})*)|0)(?:[\.\,]\d+)($|\s)?
I think the best regex for your condition will be :
^[\d]+(?:,\d+)*(?:\.\d+)?$
this will validate whatever you like
and at the same time:
not validate:
numbers ending in ,
numbers ending in .
numbers having . before comma
numbers having more than one decimal points
check out the demo here : http://regex101.com/r/zI0mJ4
Your format is a bit strange as it is not a standard format.
My first thought was to put a float instead of a string and put a Range validation attribute to avoid negative number.
But because of formatting, not sure it would work.
Another way is the regex, of course.
The one you propose means :
"some numbers then possibly a group formed by a dot and two numbers exactly".
This is not what you exepected.
Strictly fitted your example of a number lower than 100,000.99 one regex could be :
^[0-9]{1-2}[\.,][0-9]{3}([\.,][0-9]{1-2})?$
A more global regex, that accept all positive numbers is the one posted by Avinash Raj : (?:\d|[,\.])+

Regex for decimal (square meter) values

I got a regex that fails on validating my input.
My regex: \d{1,5}([\.,]\d{0,2})?
It should validate square meters (decimal values) with a separator of either . or , and should allow up to five digits (and at least one) before the separator and up to two after it.
So it should accept:
1
1,0
1.0
12345
12345,10
12345.10
But not
.1
123456
12345,123
In the group you're capturing, ([\.,]\d{0,2})?, you allow the numbers to appear between 0 and 2 times, however, the entire group is marked as optional per the ending ?. Because of this, the range should be set to {1,2} instead:
\d{1,5}([\.,]\d{1,2})?
If your input is specifically a number (and not a full sentence), I would also recommend adding a leading ^ and an ending $. This will force the regex to check from the start of the string to the end (respectively). The final regex should be:
^\d{1,5}([\.,]\d{1,2})?$
If you're using this regex for more than validation and also want to view the matched values, you should change the current group that's matching (the decimal portion) to a non-matching group (change ( to (?:) and then add parentheses around the full regex:
^(\d{1,5}(?:[\.,]\d{1,2})?)$
You were close. The correct regex for that behaviour would be:
^\d{1,5}(?:[\.,]\d{0,2})?$
A good tool for tinkering with Regex's for .Net: Expresso. http://www.ultrapico.com/Expresso.htm

Categories

Resources