I need help on regular expression to allow number with character - java

condition:
123 not valid
123 A valid
abc123 valid
abc123Ab valid
I have to apply regular expression compulsory character with number?

This will match any string starting with an optional set of digits followed by a combination of white spaces, letters and digits. But it still matches 123_ (that's 123 followed by a space `)
^\d*[\sa-zA-Z0-9]+$
The following will check if you have at least one letter in your string combined with optional digits, white spaces and letters.
[a-zA-Z\s\d]*[a-zA-Z]+?[a-zA-Z\s\d]*
[a-zA-Z\s\d] match a single character present in [].
Quantifier * : Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]

(([a-zA-Z\s])*(\d{1,})([a-zA-Z\s]){1,}|([a-zA-Z\s]){1,}(\d{1,})([a-zA-Z\s])*)
first part of this expression will ensure string can start without any letters but atleast 1 digit must be present and should end with 1 or many letters. second part will ensure string can start with atleast 1 letter followed by atleast 1 digit and then followed by 0 or any number of letters.

Related

Constructing regex in Java with variable number of certain characters in pattern

So a text file is given that should follow some a priori known format. I would like to check that such a text file indeed follows the format by reading each line in the text file and comparing to a regex. So, the first line in each text file is on the following format:
First character is "O" (capital o)
Characters 2-16 are numbers, with the exception of the 6:th character which is a blank space
Characters 17-30 is a decimal number, where character 28 is a decimal point
Characters 31-40 is an integer number
...
The specification continues, however I only need help with steps 3 and 4. For instance, a decimal number could be 1000.55, but in the text file it would be preceded by 7 blank spaces so that it fits the format. The same goes for step 4: if the number is 10, then this would be preceded by 8 blank spaces in the text file so that it fits.
How can I construct a regex that detects this pattern? Since the number of blank spaces may change, I am not sure. My idea was something like this:
String regex = "O[0-9]{4} [0-9]{10}[ ]*[0-9]*,[0-9]{2}"
The first letter is "O", followed by four digits, then a blank space, then 10 digits, then an unspecified number of blank spaces followed by an unspecified number of digits. Then finally decimal point and two digits. But this does not restrict the decimal number to only 14 characters! This is unfortunate, I do not think it will work.
You could match the first part for which you know the amount of occurrences.
For step 3 and 4 you could make use of positive lookaheads to assert the amount of occurrences.
In Java you could also use \h to match a horizintal whitespace char.
^O\d{4} \d{10}(?=[ \d]{11}\.) *\d*\.\d\d(?=[ \d]{10}) {0,9}\d+
In Java with the doubled backslashes:
String regex = "^O\\d{4} \\d{10}(?=[ \\d]{11}\\.) *\\d*\\.\\d\\d(?=[ \\d]{10}) {0,9}\\d+";
^O Match O at the start of the string
\d{4} \d{10} Match 4 digits, a space and 10 digits
(?=[ \d]{11}\.)
*\d*\.\d\d Match optional spaces . and 2 digits (If only .22 should also match)
(?=[ \d]{10}) Positive lookahead, assert 10 occurrences of either a space or digit to the right from the current position
{0,9}\d+ Match 0-9 spaces and 1+ digits
Regex demo
If the length of the string is a total of 40 characters, you can use a single lookahead (?=[ \d]{11}\.) because the string length is 40 characters.
^O(?=[\d .]{39}$)\d{4} \d{10}(?=[ \d]{11}\.) *\d*\.\d\d *\d+$
Regex demo

At least 1 capital, followed by numeric, optional dashes and space

I want to implement regex which allows only capital, numeric, optional dash and space.
Format is: At least 1 capital, followed by numeric and optional dash and space.
I tried
/^[A-Z0-9- ]+$/
But it's not working. Can anyone please help. Thanks in advance.
You have mentioned "Atleast 1 capital followed by numeric and optional dash and space"
this is the regular expression for at least one Capital letter at first followed by any number of letters, hypens and spaces
^[A-Z][a-zA-Z0-9 -]*$
In case you meant Capital letter at any position,
this is the regular expression for at least one Capital letter at any position , and only containing zero or more letters[upper and lowercase] , numbers, space and hyphen at other positions
^[a-zA-Z0-9 -]*[A-Z][a-zA-Z0-9 -]*$
This is valid
This is valid 2
This is n*t valid
thiS is valid 3
this Is -4 valid
This + is not VALID.
--- this is Valid 2 --

Regular expression that accepts only two digit integer or a floating number

I am trying to validate a text field that accepts number like 10.99, 1.99, 1, 10, 21.
\d{0,2}\.\d{1,2}
Above expression is only passing values such as 10.99, 11.99,1.99, but I want something that would satisfy my requirement.
Try this:
^\d{1,2}(\.\d{1,2})?$
^ - Match the start of string
\d{1,2} - Must contains at least 1 digit at most 2 digits
(\.\d{1,2}) - When decimal points occur must have a . with at least 1 and at most 2 digits
? - can have zero to 1 times
$ - Match the end of string
Assuming you don't want to allow edge cases like 00, and want at least 1 and at most 2 decimal places after the point mark:
^(?!00)\d\d?(\.\d\d?)?$
This precludes a required digit before the decimal point, ie ".12" would not match (you would have to enter "0.12", which is best practice).
If you're using String#matches(), you can drop the leading/trailing ^ and $, because that method must to match the entire string to return true.
First \d{0,2} does not seem to fit your requirement as in that case it will be valid for no number as well. It will give you the correct output but logically it does not mean to check no number in your string so you can change it to \d{1,2}
Now, in regex ? is for making things optional, you can use it with individual expression like below:
\d{1,2}\.?\d{0,2}
or you can use it on the combined expression like below
\d{1,2}(\.\d{1,2})?
You can also refer below list for further queries:
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abc|def) Matches abc or def
Useful link : https://regexone.com/
Can you try using this :
(\d{1,2}\.\d{1,2})|(\d{1,2})
Here is a Demo, you can check also simple program
You have two parts or two groups one to check the float numbers #.#, #.##, ##.##, ##.# and the second group to check the integer #, ##, so we can use the or |, float|integer
I think patterns of this type are best handled with alteration:
/^\s*([-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?)$ #float
| # or
^(\d{1,2})$ # 2 digit int/mx
Demo

regular expression not containing two or more consecutive comma or hyphen and between numbers at most one hyphen

I have scenario to validate number range, it can be multiple range or single number.
Ex number 1 to 10 can be written as (1-3,4,5-8,9,10) here 1-3 indicates rage (1,2,3) I have tried java regex :
Pattern.matches("^[0-9][0-9,-]*,[0-9,-]*[0-9]$","11,131-132-134,45,12--10,,10");
this pattern allows consecutive hyphen and comma,
Valid Input
1) 1-3,4,5-8,9,10
2) 1-3,4-5,6-10
3) 1,2,3,4,5
4) 1,2-5,6
Invalid Input
1) ,2,3,4-10,
2) -2,3,4-10-
3) 2,3,,4-10
4) 2,3,4--10
5) 2,3,4-6-10 (Invalid range)
can someone suggest how to check the comma and hyphen should not appear two times consecutively, start and end with number, range should not repeat (4-8-10)
This should be the regex you want:
^\\d+(-\\d+)?(,\\d+(-\\d+)?)*$
It checks for the following sequence:
\\d+ : One or more digits
(-\\d+)? : An optional sequence of hyphen followed by one or more digits
(,\\d+(-\\d+)?)* : Zero or more occurrence of a comma followed by one or more digits followed by an optional sequence of hyphen followed by one or more digits
As the regex looks for a digit at the beginning, a string starting with hyphen or comma will not be allowed.
As it looks for a digit to be immediately followed by a hyphen and comma, a string having consecutive hyphens or commas, a hyphen immediately followed by a comma or the reverse would not be allowed.
As the ? in (-\\d+)?allows exactly zero or one occurrence of the (-\\d+) sequence, a range like 1-2-3 will not be matched.
If you don't need to allow a single number alone, replace the * in ^\\d+(-\\d+)?(,\\d+(-\\d+)?)*$ with +.
A repeated group is a simple way to validate a string of a repeating sequence:
(?:\\d+(?:-\\d+)?,)+(?:\\d+(?:-\\d+)?$)
Live demo

Regexp: Limiting where and how often certain chars are allowed

I have some form numbers I need to validate. I've tried multiple attempts but am not getting it right yet. While much is allowed in a form number there are some limits I need to impose:
All of these rules should be enforced:
A-Z allowed but not required (see bullet 4)
0-9 allowed but not required (see bullet 4)
period (decimal point) and dash, if present, only allowed once per form number . -
Minimum length is one character and it cannot be a space, dash or period
multiple spaces are allowed but two spaces may not be next to each other; also no leading or trailing spaces are allowed
This is what I had before but not all the above rules were enforced.
[A-Z0-9]([A-Za-z0-9 -.])*[A-Z0-9]
So these would be examples of valid form numbers under the new requirements:
123
123 456
A1 IL 23 MN
CL-100 2.0
These would be examples of invalid form numbers under the new requirements:
123 456
25! 25
25-IL 30-1
aa bb CC
This should work
^([A-Z0-9]|(?! )(?!.* $)(?!.* )(?!.*-.*-)(?!.*\..*\.)(?![.-]$)[A-Z0-9 .-]+)$
There are two parts. The first one [A-Z0-9] checks for a single character. If it isn't a single character then there are some exclusion rules (?! )(?!.* $)(?!.* )(?!.*-.*-)(?!.*\..*\.)(?![.-]$) (in order): no beginning with space, no ending with space, no consecutive double spaces, no two -, no two ., no single character . or - followed by end-of-string. Then there is the "base" pattern (one or more of) [A-Z0-9 .-]+
Note that you'll have to escape the \ with another \, so \\.
Does it have to be all in one regex for some reason? You could go through and match for \s\s, and make sure that returns false. then you can go through each character and make sure that not more than 1 of them is a . and not more than one of them is a -. You can also check for no leading or trailing spaces, or you can be kind to your users and simply trim the input. You can then make sure that you have at least one character, and if the length is exactly one character, it is not a dash or a period.
Finally, since all of your other conditions are now satisfied, you can match the string against [A-Z0-9 -.]* and you will have your answer.
Based on your unsuccessful regex, I suspect you have a lot more conditions you actually want met, but hopefully this was enough help to allow you to figure out how to meet them on your own.

Categories

Resources