Regex to match optional parameter - javascript

I'm trying to write a regex to match an optional parameter at the end of a path.
I want to cover the first 4 paths but not the last one:
/main/sections/create-new
/main/sections/delete
/main/sections/
/main/sections
/main/sectionsextra
So far I've created this:
/\/main\/sections(\/)([a-zA-z]{1}[a-zA-z\-]{0,48}[a-zA-z]{1})?/g
This only finds the first 3. How can I make it match the first 4 cases?

You may match the string in question up the optional string starting with / with any 1 or or more chars other than / after it up to the end of the string:
\/main\/sections(?:\/[^\/]*)?$
^^^^^^^^^^^^^^
See the regex demo. If you really need to constrain the optional subpart to only consist of just letters and - with the - not allowed at the start/end (with length of 2+ chars), use
/\/main\/sections(?:\/[a-z][a-z-]{0,48}[a-z])?$/i
Or, to also allow 1 char subpart:
/\/main\/sections(?:\/[a-z](?:[a-z-]{0,48}[a-z])?)?$/i
Details
\/main\/sections - a literal substring /main/sections
(?:\/[^\/]*)? - an optional non-capturing group matching 1 or 0 occurrences of:
\/ - a / char
[^\/]* - a negated character class matching any 0+ chars other than /
$ - end of string.
JS demo:
var strs = ['/main/sections/create-new','/main/sections/delete','/main/sections/','/main/sections','/main/sectionsextra'];
var rx = /\/main\/sections(?:\/[^\/]*)?$/;
for (var s of strs) {
console.log(s, "=>", rx.test(s));
}

Related

How do I make an query parameter optional in regex?

i have this regex:
^https?:path\?id=([a-zA-Z0-9._]+)&?.*&gl=([^&|\n|\t\s]+)&?.*$
the query parameter:
?id=([a-zA-Z0-9._]+)&?.*&gl=([^&|\n|\t\s]+)&?.*$
how do i make "gl" to be optional?
You can use
^https?:path\?id=([^&]+)(?:.*?(?:&gl=([^&\s]+).*)?)?$
See the regex demo.
Details:
^ - start of string
http - a fixed http string
s? - an optional s char
:path\?id= - a fixed :path?id= string
([^&]+) - Group 1: one or more chars other than a & char
(?:.*?(?:&gl=([^&\s]+).*)?)? - an optional sequence of
.*? - any zero or more chars other than line break chars as few as possible
(?:&gl=([^&\s]+).*)? - an optional sequence of
&gl= - a fixed string
([^&\s]+) - Group 2: one or more chars other than whitespace and &
.* - any zero or more chars other than line break chars as many as possible
$ - end of string.

“combine” 2 regex with a logic or?

I have two patterns for javascript:
/^[A-z0-9]{10}$/ - string of exactly length of 10 of alphanumeric symbols.
and
/^\d+$/ - any number of at least length of one.
How to make the expression of OR string of 10 or any number?
var pattern = /^([A-z0-9]{10})|(\d+)$/;
doesn't work by some reason. It passes at lest
pattern.test("123kjhkjhkj33f"); // true
which is not number and not of length of 10 for A-z0-9 string.
Note that your ^([A-z0-9]{10})|(\d+)$ pattern matches 10 chars from the A-z0-9 ranges at the start of the string (the ^ only modifies the ([A-z0-9]{10}) part (the first alternative branch), or (|) 1 or more digits at the end of the stirng with (\d+)$ (the $ only modifies the (\d+) branch pattern.
Also note that the A-z is a typo, [A-z] does not only match ASCII letters.
You need to fix it as follows:
var pattern = /^(?:[A-Za-z0-9]{10}|\d+)$/;
or with the i modifier:
var pattern = /^(?:[a-z0-9]{10}|\d+)$/i;
See the regex demo.
Note that grouping is important here: the (?:...|...) makes the anchors apply to each of them appropriately.
Details
^ - start of string
(?: - a non-capturing alternation group:
[A-Za-z0-9]{10} - 10 alphanumeric chars
| - or
\d+ - 1 or more digits
) - end of the grouping construct
$ - end of string

convert Golang regex to JS regex

I have a regex from Golang (nameComponentRegexp). How can I convert it to JavaScript style regex?
The main blocking problem for me:
How can I do optional and repeated in JavaScript correctly
I tried copy from match(`(?:[._]|__|[-]*)`) but it cannot match single period or single underscore. I tried it from online regex tester.
The description from Golang:
nameComponentRegexp restricts registry path component names to start
with at least one letter or number, with following parts able to be
separated by one period, one or two underscore and multiple dashes.
alphaNumericRegexp = match(`[a-z0-9]+`)
separatorRegexp = match(`(?:[._]|__|[-]*)`)
nameComponentRegexp = expression(
alphaNumericRegexp,
optional(repeated(separatorRegexp, alphaNumericRegexp)))
Some valid example:
a.a
a_a
a__a
a-a
a--a
a---a
See how you build the nameComponentRegexp: you start with alphaNumericRegexp and then match 1 or 0 occurrences of 1 or more sequences of separatorRegexp+alphaNumericRegexp.
optional() does the following:
// optional wraps the expression in a non-capturing group and makes the
// production optional.
func optional(res ...*regexp.Regexp) *regexp.Regexp {
return match(group(expression(res...)).String() + `?`)
}
repeated() does this:
// repeated wraps the regexp in a non-capturing group to get one or more
// matches.
func repeated(res ...*regexp.Regexp) *regexp.Regexp {
return match(group(expression(res...)).String() + `+`)
}
Thus, what you need is
/^[a-z0-9]+(?:(?:[._]|__|-*)[a-z0-9]+)*$/
See the regex demo
Details:
^ - start of string
[a-z0-9]+ - 1 or more alphanumeric symbols
(?:(?:[._]|__|-*)[a-z0-9]+)* - zero or more sequences of:
(?:[._]|__|-*) - a ., _, __, or 0+ hyphens
[a-z0-9]+- 1 or more alphanumeric symbols
If you want to disallow strings like aaaa, you need to replace all * in the pattern (2 occurrences) with + (demo).
JS demo:
var ss = ['a.a','a_a','a__a','a-a','a--a','a---a'];
var rx = /^[a-z0-9]+(?:(?:[._]|__|-*)[a-z0-9]+)*$/;
for (var s of ss) {
console.log(s,"=>", rx.test(s));
}

How to use RegEx to ignore the first period and match all subsequent periods?

How to use RegEx to ignore the first period and match all subsequent periods?
For example:
1.23 (no match)
1.23.45 (matches the second period)
1.23.45.56 (matches the second and third periods)
I am trying to limit users from entering invalid numbers. So I will be using this RegEx to replace matches with empty strings.
I currently have /[^.0-9]+/ but it is not enough to disallow . after an (optional) initial .
Constrain the number between the start ^ and end anchor $, then specify the number pattern you require. Such as:
/^\d+\.?\d+?$/
Which allows 1 or more numbers, followed by an optional period, then optional numbers.
I suggest using a regex that will match 1+ digits, a period, and then any number of digits and periods capturing these 2 parts into separate groups. Then, inside a replace callback method, remove all periods with an additional replace:
var ss = ['1.23', '1.23.45', '1.23.45.56'];
var rx = /^(\d+\.)([\d.]*)$/;
for (var s of ss) {
var res = s.replace(rx, function($0,$1,$2) {
return $1+$2.replace(/\./g, '');
});
console.log(s, "=>", res);
}
Pattern details:
^ - start of string
(\d+\.) - Group 1 matching 1+ digits and a literal .
([\d.]*) - zero or more chars other than digits and a literal dot
$ - end of string.

Replace last character of a matched string using regex

I am need to post-process lines in a file by replacing the last character of string matching a certain pattern.
The string in question is:
BRDA:2,1,0,0
I'd like to replace the last digit from 0 to 1. The second and third digits are variable, but the string will always start BRDA:2 that I want to affect.
I know I can match the entire string using regex like so
/BRDA:2,\d,\d,1
How would I get at that last digit for performing a replace on?
Thanks
You may match and capture the parts of the string with capturing groups to be able to restore those parts in the replacement result later with backreferences. What you need to replace/remove should be just matched.
So, use
var s = "BRDA:2,1,0,0"
s = s.replace(/(BRDA:2,\d+,\d+,)\d+/, "$11")
console.log(s)
If you need to match the whole string you also need to wrap the pattern with ^ and $:
s = s.replace(/^(BRDA:2,\d+,\d+,)\d+$/, "$11")
Details:
^ - a start of string anchor
(BRDA:2,\d+,\d+,) - Capturing group #1 matching:
BRDA:2, - a literal sunstring BRDA:2,
\d+ - 1 or more digits
, - a comma
\d+, - 1+ digits and a comma
\d+ - 1+ digits.
The replacement - $11 - is parsed by the JS regex engine as the $1 backreference to the value kept inside Group 1 and a 1 digit.

Categories

Resources