Javascript regex to replace last digit occurence between square brackets? - javascript

I've been looking for this for hours, right now I've ended in a very ugly way (but working). I would like to find a reusable nice way to do this.
I've a string like this:
wanna[0].some[0].javascript
I would like to replace the last digit occurence between square brackets:
wanna[0].some[1].javascript
I've ended this (ugly) way:
myString.replace(/\d].javascript$/, "1].javascript")
which should be the best regex to match that?
myString.replace(/\d/, 1) // this should be for the first digit
myString.replace(/\d/g, 1) // this for every digit
I've read about negative look-ahead but I still didn't get if JS supports this.

Just use a negative lookahead to ascertain that there are no more brackets after the one you're matching:
var text = 'wanna[0].some[0].javascript';
text = text.replace(/\[\d](?!.*\[)/, '[1]');
Here's the fiddle: http://jsfiddle.net/bRkEP/

Not sure why you need lookahead. The answer you gave (though ugly) should work. As Crockford says of negative lookaheads in JavaScript: The Good Parts: 'This is not a good part.'
If the line you provided isn't working I imagine it's because you haven't escaped the square bracket. It should be:
myString.replace(/\d\].javascript$/, "1].javascript");
You could also do some capturing to make it easier on the eye.
I agree with the comment to your question that it seems like an odd problem to solve. Why are you changing the number in a string? This looks like something that would be better served with a number variable in the square brackets that you can then increment.

Related

Regular expressions (regex) for string starting with three dots

I have an array of strings in java script and I need to find those that start with three dots.
Then I need to delete these dots and everything after "?".
Example:
"...how to do this? - Th0be [22.2.2022]" -> "how to do this?"
For the first part I tried the ^\. regex (reference to Regular expressions: Matching strings starting with dot (.)?), but this should be only for one dot and it did not work anyway.
For the second part, I figured out the [^?]*$ regex. It looks correct, but I put it here just to be sure.
I am beginner with regex.
Any idea, how to do mainly first part?
You can use ^\.{3} to match 3 dots.
let s = "...how to do this? - Th0be [22.2.2022]";
console.log(s.replace(/^\.{3}([^?]*\?).*/, "$1"));

Don't match if there's a "period" between "word" and "?"

Perhaps he hadn't. [Perhaps he didn't?]
Perhaps he didn't.
[Perhaps he hadn't?]
I want to match the bits in brackets; sentences that start with "Perhaps" and end with a question mark.
I thought this regex would work: Perhaps.*(?!=\.)\?
However, what I'm getting is this:
[Perhaps he hadn't. Perhaps he didn't?]
Perhaps he didn't.
[Perhaps he hadn't?]
Why is this? And how to fix it?
https://regexr.com/5dfhs
You may use a negated character class like this:
/Perhaps[^.?]*\?/g
RegEx Demo
To match complete word use:
/\bPerhaps[^.?]*\?/
And to avoid matching across lines use:
/\bPerhaps[^.?\r\n]*\?/
here [^.?] would match any character except . and ?
About your regex:
(?!=\.) is actually wrong syntax for a negative lookahead. It just means don't match if we have a literal = and . ahead.
Even if you correct it to use Perhaps.*(?!\.)\? it will still not work because (?!\.) will only be applied for matching ? and that will always succeed.
Though not recommended but if you really want to use a negative lookahead then use:
/Perhaps(?:(?!\.).)*\?/

Regex finding the last string that doesnt contain a number

Usually in my system i have the following string:
http://localhost/api/module
to find out the last part of the string (which is my route) ive been using the following:
/[^\/]+$/g
However there may be cases where my string looks abit different such as:
http://localhost/api/module/123
Using the above regex it would then return 123. When my String looks like this i know that the last part will always be a number. So my question is how do i make sure that i can always find the last string that does not contain a number?
This is what i came up with which really stricty matches only module for the following lines:
http://localhost/api/module
http://localhost/api/module/123
http://localhost/api/module/123a
http://localhost/api/module/a123
http://localhost/api/module/a123a
http://localhost/api/module/1a3
(?!\w*\d\w*)[^\/][a-zA-Z]+(?=\/\w*\d+\w*|$)
Explanation
I basically just extended your expression with negative lookahead and lookbehind which basically matches your expression given both of the following conditions is true:
(?!\w*\d\w*) May contain letters, but no digits
[a-zA-Z]+ Really, truly only consists of one or more letters (was needed)
(?=\/\d+|$)The match is either followed by a slash, followed by digits or the end of the line
See this in action in my sample at Regex101.
partYouWant = urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
Here it is in action:
urlString="http://localhost/api/module/123"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"
urlString="http://localhost/api/module"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"
It just uses a capture expression to find the last non-numeric part.
It's going to do this too, not sure if this is what you want:
urlString="http://localhost/api/module/123/456"
urlString.replace(/^.*\/([a-zA-Z]+)[\/0-9]*$/,'$1')
-->"module"
/([0-9])\w+/g
That would select the numbers. You could use it remove that part from the url. What language are you using it for ?

Regex testing for special characters

I'm trying to write a regex to test for certain special characters, but I think I am overcomplicating things. The characters I need to check for are: &<>'"
My current regex looks like such:
/&<>'"/
Another I was trying is:
/\&\<\>\'\"/
Any tips for a beginner (in regards to regex)? Thanks!
You are looking for a character class:
/[&<>'"]/
In doing so, any of the characters in the square brackets will be matched.
The expression you were originally using, /&<>'"/, wasn't working as expected because it matches the characters in that sequential order. In other words, it would match a full string such as &<>'" but not &<.
I'm assuming that you want to be able to match all of the characters you listed, at one time.
If so, you should be able to combine a character set with the g (global-matching) flag, for your regex.
Here's what it could look like:
/[<>&'"]/g
Try /(\&|\<|>|\'|\")/
it depends on what regex system you use

Regular expression handle multiple matches like one, how to fix?

I have a regex, and a string that includes some matches for this regex. My regex handle all this matches like it is only one big match (of course I don't want such behaviour), let me show you an example:
My test string (sorry for scribble, but this doesn't matter):
sdfsd -dsf- sdfsdfssdfsfdsfsd -sdfsdf-
my regex in js code:
view.replace(/(\-(.+)\-)/g, '<span style="background-color:yellow">$1</span>');
my result:
sdfsd<span style="background-color:yellow">-dsf- sdfsdfssdfsfdsfsd -sdfsdf-</span>
As you can see each of this strings in the "-" must be enclosed in span, but there is only one span. How I can fix this? (honestly I don't want change my (.+) regex part, which I think might be a problem, but if there is no other way to do this, let me know).
In other words, result must be:
sdfsd<span style="background-color:yellow">-dsf-</span> sdfsdfssdfsfdsfsd <span style="background-color:yellow">-sdfsdf-</span>
Feel free to ask me in the comments, and thanks for your help.
honestly I don't want change my (.+) regex part, which I think might be a problem
Why not, it is actually the source of the problem, you can try the following regex which would work:
/(\-([^-]+)\-)/g
and if you think that dashes - can appear between - and - themselves then you can use the less efficient:
/(\-(.+?)\-)/g
+? causes a lazy match, or in other words after matching the initial -, then .+? matches a single character then it moves control to the following - which tries to match a dash, if it couldn't then .+? reads (consumes) another character from the input and so on until the following - is able to match.
You can try:
view.replace(/-([^-]+)-/g, '<span style="background-color:yellow">$1</span>');

Categories

Resources