regex sets of 5 digits followed by a comma (trailing comma optional) - javascript

I've got the following regex:
(\d{5}[,])
This matches the following:
12005,11111,11111,
but how do I make the trailing comma optional?
EDIT:
Acceptable results would be:
12005,
11111,11111,
12005
11111,11111
Unacceptable:
123456
123456,
12345,123456
123456,123456

(\d{5})(?:,|$)
should do the trick.
To break this down,
\d{5} - 5 digits
(?:...) - just using parentheses to surround the |
, - a literal comma
$ - end of input
,|$ - a comma or end of input.
The |$ part is needed to avoid spuriously matching groups of digits not separated by commas like "01234567889".
To see it in action, try
JSON.stringify(
["01234", "01234,", "01234,56789", "01234,56789", "", "0123456789"]
.filter(
function (s) {
return /^(?:(\d{5})(?:,|$))+$/.test(s);
}))
which uses a larger RegExp to match one or more of these groups, so emits
["01234","01234,","01234,56789","01234,56789"]

(\d{5}[,]?)
Will match
12005,11111,11111,
or
12005,11111,11111

Perhaps this:
((?:\d{5},)*\d{5})
Will work if one set of 5 numbers or more than one separated by commas. Or you could get fully explicit and slap the start and end on it:
^((?:\d{5},)*\d{5})$

to make sure you don't match 5 digits from numbers with 6 or more digits, use a word boundary assertion (\b) and beginning of line assertion (^), like so:
(?:\b|^)(\d{5})(?:,|$)

\d{5}[,]* - 0 or more or \d{5}[,]? - 0 or 1.

Related

Javascript Regular Expresion [duplicate]

I'm trying to write a RegExp to match only 8 digits, with one optional comma maybe hidden in-between the digits.
All of these should match:
12345678
12,45678
123456,8
Right now I have:
^[0-9,]{8}
but of course that erroneously matches 012,,,67
Example:
https://regex101.com/r/dX9aS9/1
I know optionals exist but don't understand how to keep the 8 digit length applying to the comma while also keeping the comma limited to 1.
Any tips would be appreciated, thanks!
To match 8 char string that can only contain digits and an optional comma in-between, you may use
^(?=.{8}$)\d+,?\d+$
See the regex demo
The lookahead will require the string to contain 8 chars. ,? will make matching a comma optional, and the + after \d will require at least 1 digit before and after an optional comma.
If you need to match a string that has 8 digits and an optional comma, you can use
^(?:(?=.{9}$)\d+,\d+|\d{8})$
See the regex demo
Actually, the string will have 9 characters in the string (if it has a comma), or just 8 - if there are only digits.
Explanation:
^ - start of string
(?:(?=.{9}$)\d+,\d+|\d{8}) - 2 alternatives:
(?=.{9}$)\d+,\d+ - 1+ digits followed with 1 comma followed with 1+ digits, and the whole string matched should be 9 char long (8 digits and 1 comma)
| - or
\d{8} - 8 digits
$ - end of string
See the Java code demo (note that with String#matches(), the ^ and $ anchors at the start and end of the pattern are redundant and can be omitted since the pattern is anchored by default when used with this method):
List<String> strs = Arrays.asList("0123,,678", "0123456", // bad
"01234,567", "01234567" // good
);
for (String str : strs)
System.out.println(str.matches("(?:(?=.{9}$)\\d+,\\d+|\\d{8})"));
NOTE FOR LEADING/TRAILING COMMAS:
You just need to replace + (match 1 or more occurrences) quantifiers to * (match 0 or more occurrences) in the first alternative branch to allow leading/trailing commas:
^(?:(?=.{9}$)\d*,\d*|\d{8})$
See this regex demo
You can use following regex if you want to let trailing comma:
^((\d,?){8})$
Demo
Otherwise use following one:
^((\d,?){8})(?<!,)$
Demo
(?<!,) is a negative-lookbehind.
/^(?!\d{0,6},\d{0,6},\d{0,6})(?=\d[\d,]{6}\d).{8}$/
I guess this cooperation of positive and negative look-ahead does just what's asked. If you remove the start and end delimiters and set the g flag then it will try to match the pattern along decimal strings longer than 8 characters as well.
Please try http://regexr.com/3d63m
Explanation: The negative look ahead (?!\d{0,6},\d{0,6},\d{0,6}) tries not to find any commas side by side if they have 6 or less decimal characters in between while the positive look ahead (?=\d[\d,]{6}\d) tries to find 6 decimal or comma characters in between two decimal characters. And the last .{8} selects 8 characters.

Catching start number and final number

i'm trying to create a regex to catch the first number in the line and the last one, but i'm having some problem with the last one:
The lines look like this:
00005 SALARIO MENSAL 17030 36.397.291,92 36.397.291,92
00010 HORAS TRABALHADAS 0798 19.731,93 19.731,93
And this is my regex:
(^\d+).*(\d)
As you can see here: http://regexr.com/3crbt is not working as expected. I can get the first one, but the last is just the last number.
Thanks!
You can use
/^(\d+).*?(\d+(?:[,.]\d+)*)$/gm
See the regex demo
The regex matches:
^ - start of the line
(\d+) - captures into Group 1 one or more digits
.*? - matches any characters but a newline, as few as possible up to
(\d+(?:[,.]\d+)*) - one or more digits followed with zero or more sequences of , or . followed with one or more digits (Group 2)
$ - end of the string
The /g modifier ensures we get all matches and /m modifier makes the ^ and $ match start and end of a line respectively.
I tried the following one:
(^(\d+))|(\d+$)
And its seems to work on the regexr.com thingy. But matching them up might require some assumptions that each line has at least two numbers.
You need to make the .* non-greedy by changing it to .*? and add + to the second digit sequence match.
^(\d+).*?(\d+)$
If you want to match the full last number, use this:
^(\d+).*?([\d\.,]+)$
Example

Regular expression match 0 or exact number of characters

I want to match an input string in JavaScript with 0 or 2 consecutive dashes, not 1, i.e. not range.
If the string is:
-g:"apple" AND --projectName:"grape": it should match --projectName:"grape".
-g:"apple" AND projectName:"grape": it should match projectName:"grape".
-g:"apple" AND -projectName:"grape": it should not match, i.e. return null.
--projectName:"grape": it should match --projectName:"grape".
projectName:"grape": it should match projectName:"grape".
-projectName:"grape": it should not match, i.e. return null.
To simplify this question considering this example, the RE should match the preceding 0 or 2 dashes and whatever comes next. I will figure out the rest. The question still comes down to matching 0 or 2 dashes.
Using -{0,2} matches 0, 1, 2 dashes.
Using -{2,} matches 2 or more dashes.
Using -{2} matches only 2 dashes.
How to match 0 or 2 occurrences?
Answer
If you split your "word-like" patterns on spaces, you can use this regex and your wanted value will be in the first capturing group:
(?:^|\s)((?:--)?[^\s-]+)
\s is any whitespace character (tab, whitespace, newline...)
[^\s-] is anything except a whitespace-like character or a -
Once again the problem is anchoring the regex so that the relevant part isn't completely optionnal: here the anchor ^ or a mandatory whitespace \s plays this role.
What we want to do
Basically you want to check if your expression (two dashes) is there or not, so you can use the ? operator:
(?:--)?
"Either two or none", (?:...) is a non capturing group.
Avoiding confusion
You want to match "zero or two dashes", so if this is your entire regex it will always find a match: in an empty string, in --, in -, in foobar... What will be match in these string will be an empty string, but the regex will return a match.
This is a common source of misunderstanding, so bear in mind the rule that if everything in your regex is optional, it will always find a match.
If you want to only return a match if your entire string is made of zero or two dashes, you need to anchor the regex:
^(?:--)?$
^$ match respectively the beginning and end of the string.
a(-{2})?(?!-)
This is using "a" as an example. This will match a followed by an optional 2 dashes.
Edit:
According to your example, this should work
(?<!-)(-{2})?projectName:"[a-zA-Z]*"
Edit 2:
I think Javascript has problems with lookbehinds.
Try this:
[^-](-{2})?projectName:"[a-zA-Z]*"
Debuggex Demo

business phone regex containing if-else expression

I am trying to write business phone number regex in javascript, my requirements are:
It should contain only digits,dashes and whitespaces
It should not end with - but can end with whitespaces
There should be only 1 - between two groups
It should match numbers with and without - like 1, 123, 678-78
I have tried following regex but it fails for 123-- as it is invalid one anybody please suggest me something
/^([ ]*[0-9]+[-]?[0-9 ]*?([-])[ ]*[0-9]+[ ]*|[0-9 ]*[ ]*)+$/.test('123--2')
Try this
/^[0-9]+(-[0-9\s]+)*$/
I don't know if you still need an answer to this, but this works for your requirements:
/^(?!.+-\s*$)\s*((?:\d+\s*-?\s*)+)$/
Explanation:
^ start of string
(?!.+-\s*$) disallow - (or - followed by whitespace) at the end of the string
\s* optional leading spaces
( start capturing
(?:\d+\s*-?\s*)+ one or more groups of the following:
one or more digits,
possibly followed by whitespace,
possibly followed by a single hyphen,
possibly followed by more whitespace
) stop capturing
$ end of the string
Demo

Possible to make regular expression with sub-query

I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:
Starts with 07
Contains only numbers, whitespace or dashes
Contains exactly 11 numbers
Is this possible to do in just one regular expression and if so, how please?
I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
//string matches conditions
}
Explanation of the regex:
^: Anchor that means "match start of string".
07: Match the string 07. Together with the above, it means that the string must start with 07.
[: Beginning of a character class i.e., a set of characters that we want to allow
\d: Match a digit (equivalent to 0-9).
\-:
" ": Match whitespace (markdown doesn't let me show a single space as code)
]: End of character class.
+: One or more of the previous.
$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.
So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.
Since #Vivin throws out the challenge :
/^07([-\s]*\d){9}[-\s]*$/
^07 : begin with digits 07
( : start group
[-\s]* : any number of - or whitespace
\d : exactly one digit
){9} : exactly 9 copies of this group (11 digits including 07)
[-\s]* : optional trailing spaces or -
$ : end of string
Of course a more useful way might be as follows
if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
....
}
which has the advantage (?) of leaving just the digits in telNo
Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}
This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
() - include in capture
(?:) - do not include in capture
\s - whitespace
| - or
- - dash
* - zero or more
\d - digits only
{9} - exactly nine of what is captured

Categories

Resources