Important: I have already looked up similar questions on Stackoverflow and elsewhere and I couldnt find a solution.
I'm trying to make a regular expression that matches whatever comes after this pattern (the pattern itself excluded)
[-a-zA-Z0-9] \/[-\._a-zA-Z0-9]
I tried using ^
as a NOT operator like so:
[^([-a-zA-Z0-9] \/[-\._a-zA-Z0-9] )]
But it throws a syntax error: Unmatched '('
. Seems like it associates the first ]
with the first [
instead of with the second. How to fix this?
I also tried doing a Positive Lookbehind like so:
(?<=([-a-zA-Z0-9] \/[-\._a-zA-Z0-9] ).*)
But it's not working.
What am I doing wrong?
CodePudding user response:
You can capture all that follows the match in group 1, and use group 1 in the replacement.
[-a-zA-Z0-9] \/[-._a-zA-Z0-9] (. )
The contents of file to test with:
hello/w0rld/blbalba0
hel-lo/wor_ld?q=0
hello/w0rld)/blbalba0
hel-lo/wor_&ld?q=0(
As you mention in the comments that you want to use sed
:
sed -E 's/[-a-zA-Z0-9] \/[-._a-zA-Z0-9] (. )/\1/' file
Output:
/blbalba0
?q=0
)/blbalba0
&ld?q=0(
CodePudding user response:
const pattern = new RegExp('([-a-zA-Z0-9] \/[-\._a-zA-Z0-9] )([\/\?].*)');
if(pattern.test('hello/w0rld/blbalba0')){
console.log('Matches string 1');
}
if(pattern.test('hel-lo/wor_ld?q=0')){
console.log('Matches string 2');
}
// Invalid string
if(pattern.test('hello/w0rld)/blbalba0')){
console.log('Matches string 3');
}
// Invalid string
if(pattern.test('hel-lo/wor_&ld?q=0')){
console.log('Matches string 4');
}
// if you wish to access the matches
const matches = pattern.exec('hel-lo/wor_ld?q=0');
console.log(matches[2]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>