Regex get last 2 characters pipe not working - javascript

I'm creating a regex expression to get the variables passed to a JavaScript constructor.
The input is always going to follow along these lines:
app.use(express.static('public'));
And the regex I plan to use to strip out the unnecessary parts is:
(^app.use\()|(..$)
The first part of the regex gets everything up to the first parenthesis, and the it's supposed to pipe it to another expression which gets the last 2 characters of the string.
My issue is that it seems to be ignoring the second regex. I tried a few other expressions in the second part and they worked, but this one isn't.
What am I doing wrong?
Regex example on Regex101: https://regex101.com/r/jV9eH6/3
UPDATE:
This is not a duplicate of How to replace all occurrences of a string in JavaScript?
My question is about a specific issue with a regex, not about replacing one string with another in JavaScript.

You need to use multiline modifier. Whenever anchors ^, $ are used in your regex then feel free to add multi-line modifier m.
/(^app.use\()|(..$)/gm
DEMO

Related

In Regex How to find and replace characters when they are not within other alphabetic characters?

I'm formatting a datetime string in javascript by Regex, so I want:
Find and replace all d characters when d is not within other alphabetic characters. like this:
Find and replace all dd characters when dd is not within other alphabetic characters. like this:
I tested /\bd\b/mg pattern but its result is not which I want everytime.
How should I exclude unwanted cases in the following command:
str = str.replace(/\bd\b/mg, number);
The regular expression You posted does not consider _ as a word boundary, so it does not replace the character as expected.
In order to include this character as well, either before or after the d character to be replaced, You can use expressions similar to these:
To replace d:
/(\b|_)(d)(\b|_)/mg
To replace dd:
/(\b|_)(dd)(\b|_)/mg
Or to replace both in the same way (if it's acceptable):
/(\b|_)(d|dd)(\b|_)/mg
In comments under this answer in another thread on StackOverflow, it was also suggested to use a library that can format dates, instead of implementing it by Yourself.
UPDATE: As someone mentioned, the issue with this is also that including _ in the regular expression, removes it after the replacement. However, You can call replace and use capturing parentheses references, like this:
str.replace(/(\b|_)(d)(\b|_)/mg, "$1" + number + "$3")
I've updated earlier expressions posted in this answer to work with this method.
Please note that I'm not aware of all the cases You want to consider, so if You have any problems using the suggested solution or it does not work as expected in Your case, please let me know, so I can try to help.
I could use a lookahead and if you are not using JavaScript then a lookbehind as well.
example lookahead which checks if there is no following alpha character:
(?=[^a-zA-Z])
If you are using JavaScript it doesn't support lookbehind so you will need to use a capturing group and backreferencing.
For JS capture the part in the outermost parentheses and then use \1, \2... to target:
[^a-zA-Z](d(?=[^a-zA-Z]))
non-JS can use lookbehind:
(?<=[^a-zA-Z])d(?=[^a-zA-Z])

Regular expression requirements not strict enough

Using regex I am attampting to limit the user's input to one of the following scenarios:
http(s)://www.instagram.com/user
www.instagram.com/user
http(s)://instagram.com/user
instagram.com/user
However, once that final case is satisfied it will accept any random string before the "instagram.com", this isn't imperitive but it's more for my own peace of mind. The regular expression I am using is the following:
control.value.match(/(?:(?:http|https):\/\/)?(?:www.)?instagram.com\/([A-Za-z0-9-_]+)/igm)
I would like to have it so that only one of the above cases validate. Thanks in advance for the help.
If you want to ensure that the entire content matches a regular expression, there are a few ways, but my favorite is just using the regular expression itself.
You can use the line start ^ and line end $ characters. These are called anchors and you can read about them at http://www.regular-expressions.info/anchors.html
Your code would look like this:
control.value.match(/^(?:(?:http|https):\/\/)?(?:www.)?instagram.com\/([A-Za-z0-9-_]+)$/igm)
This only works because you're looking at a single line of text. Your m flag would imply multiline text (which doesn't make any sense with a url), so you should take a closer look at http://www.regular-expressions.info/modifiers.html. In javascript, modifiers for the entire expression are placed as flags at the end. You can see examples of that at http://www.rexegg.com/regex-modifiers.html.
In your example, your flags are igm and come after the closing /.
If you put ^ at the beginning of your regex it will not accept junk before. Because the ^ is the beginning of the line

Two-digit RegEx Patterm Match in JavaScript

The following expression:
targetString = targetString.replace(parenthesizedRegEx, "$3$1$11");
where parenthesizedRegEx is a valid parenthesized regular expression, replaces the matched text with a string that is the concatenation of the third item, the first item, the first item again, and the literal "1". It is as if it is ignoring the "two-digit" parentheses-item index "$11" and treating it as "$1" and the literal "1".
Is there some escaping or other separating that should be used?
This result occurs in FF and IE9.
Thanks for your help. I hope the answer is embarrassingly simple!!
Edit Update:
I did a jfiddle to demonstrate the issue comprehensively. The regexp I am using includes a negative lookahead assertion. It seems that when I include all the open parens for the assertion, it fails. If I include none of the insertion's open parens, it also fails. But if I include all but the assertion's initial opening paren, it works. I know that groups formed with (?:...) are not numbered. But is seems that one has to include all the other open parens within the assertion to get the count right. So you will see in the jfiddle that $11 does not work but that $10 does.
http://jsfiddle.net/pxMFx/1/
Thanks for looking at this.
This works fine for me:
var regex = /^(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w).*$/i;
alert("abcdefghijklmno".replace(regex,"$3$1$11"));
http://jsfiddle.net/J3RAa/
The key is that you need to match the whole string with your regular expression if you are targeting a specific location in it. Try taking the .* out of the above regex and you will see that it breaks the replacement.

Nice way to do this regex substitution

I'm writing a javascript function which takes a regex and some elements against which it matches the regex against the name attribute.
Let's say i'm passed this regex
/cmw_step_attributes\]\[\d*\]/
and a string that is structured like this
"foo[bar][]chicken[123][cmw_step_attributes][456][name]"
where all the numbers could vary, or be missing. I want to match the regex against the string in order to swap out the 456 for another number (which will vary), eg 789. So, i want to end up with
"foo[bar][]chicken[123][cmw_step_attributes][789][name]"
The regex will match the string, but i can't swap out the whole regex for 789 as that will wipe out the "[cmw_step_attributes][" bit. There must be a clean and simple way to do this but i can't get my head round it. Any ideas?
thanks, max
Capture the first part and put it back into the string.
.replace(/(cmw_step_attributes\]\[)\d*/, '$1789');
// note I removed the closing ] from the end - quantifiers are greedy so all numbers are selected
// alternatively:
.replace(/cmw_step_attributes\]\[\d*\]/, 'cmw_step_attributes][789]')
Either literally rewrite part that must remain the same in replacement string, or place it inside capturing brackets and reference it in replace.
See answer on: Regular Expression to match outer brackets.
Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.
Have you tried:
var str = 'foo[bar][]chicken[123][cmw_step_attributes][456][name]';
str.replace(/cmw_step_attributes\]\[\d*?\]/gi, 'cmw_step_attributes][XXX]');

Alternation operator inside square brackets does not work

I'm creating a javascript regex to match queries in a search engine string. I am having a problem with alternation. I have the following regex:
.*baidu.com.*[/?].*wd{1}=
I want to be able to match strings that have the string 'word' or 'qw' in addition to 'wd', but everything I try is unsuccessful. I thought I would be able to do something like the following:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
but it does not seem to work.
replace [wd|word|qw] with (wd|word|qw) or (?:wd|word|qw).
[] denotes character sets, () denotes logical groupings.
Your expression:
.*baidu.com.*[/?].*[wd|word|qw]{1}=
does need a few changes, including [wd|word|qw] to (wd|word|qw) and getting rid of the redundant {1}, like so:
.*baidu.com.*[/?].*(wd|word|qw)=
But you also need to understand that the first part of your expression (.*baidu.com.*[/?].*) will match baidu.com hello what spelling/handle????????? or hbaidu-com/ or even something like lkas----jhdf lkja$##!3hdsfbaidugcomlaksjhdf.[($?lakshf, because the dot (.) matches any character except newlines... to match a literal dot, you have to escape it with a backslash (like \.)
There are several approaches you could take to match things in a URL, but we could help you more if you tell us what you are trying to do or accomplish - perhaps regex is not the best solution or (EDIT) only part of the best solution?

Categories