Question

I need help with Regex. I have words like "testBla", "Bla" and test".
I want to cut the "test" from the "testBla". So it should only remove the "test" if the given string is larger than 4 characters. This is what i have:

^test\w{4,}

but it doesn't work.

Any ideas?

Was it helpful?

Solution

If you want to remove test if it occurs at the start of the line and is followed by a word character then you could use a non-word-boundary:

^test\B

See it working online: rubular

If you want to remove test if it occurs at the start of the line and is followed by any character (except a new line) then you could use a lookahead:

^test(?=.)

See it working online: rubular

OTHER TIPS

This one will only capture the 'test' part in a word: \btest(?=\w{4,}). I'm assuming you're using a regex engine that has zero length lookahead.

Assuming you're using JavaScript, try this:

string.replace(/test([^]+)/i, "$1");

       'Bla'.replace(/test([^]+)/i, "$1"); // 'Bla'
      'test'.replace(/test([^]+)/i, "$1"); // 'test'
   'testBla'.replace(/test([^]+)/i, "$1"); // 'Bla'
   'blaTest'.replace(/test([^]+)/i, "$1"); // 'blaTest'
'blaTestbla'.replace(/test([^]+)/i, "$1"); // 'blaTestbla'

This will remove test from the string, only if the string starts with test, and only if there's more in the string than only test. I added i to make the regex case-insensitive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top