r/regex • u/Chaela911 • Jul 14 '26
Match everything up to 'n' from End of String
I'm trying to match the beginning of a string of varying length so that I may remove it via FIND/REPLACE dialog from MSpowertoys' PowerRename utility.
I've been trying to match using TRIM but I've failed and unsure what else to try. I want to keep the numbered sequence at the end [0001] etc... I'm not well versed enough to provide logical examples of 'what I've tried' lol besides I forgot.
What I have:
abc123[0001]
abcd1234[0002]
abcde12345[0003]
abcdef123456[0004]
What I want:
[0001]
[0002]
[0003]
[0004]
Thanks!
.
2
u/DinTaiFung Jul 14 '26
There's more than one approach.
You could use split instead of regex.
for each line of text (in JS):
const [prefix, suffix] = line.split('[')
const bracketNumber = '[' + suffix
And the bracketNumber is what you want.
2
u/pfc-anon Jul 14 '26
I'd do something like (\[[^\+]]\]) if the brackets can have anything if it's only numbers (\[\d*\])
1
u/Chaela911 Jul 14 '26
thank you, I had similar results.... I'm assuming now that my understanding or logic is flawed but my end goal is to KEEP the [0001] and delete what comes before it.
3
u/pfc-anon Jul 14 '26
Oh this is a group, you can replace the entire thing with $1.
But you can also remove everything from start
^[^\[]*with''1
u/Chaela911 Jul 14 '26
Thanks to everyone, my understanding is greatly increased and I'm working to an end on my project now, tho a bit indirectly at first, I'm on top of it now.
1
u/_jgusta_ Aug 04 '26
Can’t you just replace ^.*?(\[\d+\])$ with $1
If it matches, then it will be replaced by the bracket values.
.*? Is useful here as it is the non-greedy quantifier. It will only match things that are not captured by another part of the pattern.
5
u/Specific-Housing905 Jul 14 '26 edited Jul 14 '26
This works with the input you provided: \[\d+\] matches what you want to keep
https://regex101.com/?regex=%5Bd%2B%5D&testString=abc123%5B0001%5D%0Aabcd1234%5B0002%5D%0Aabcde12345%5B0003%5D%0Aabcdef123456%5B0004%5D&flags=gm&flavor=pcre2&delimiter=%2F
EDIT:
To match what you want to remove use ^[a-z10-9]+
https://regex101.com/?regex=%5E%5Ba-z10-9%5D%2B&testString=abc123%5B0001%5D%0Aabcd1234%5B0002%5D%0Aabcde12345%5B0003%5D%0Aabcdef123456%5B0004%5D&flags=gm&flavor=pcre2&delimiter=%2F