1

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?

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Sylnois
  • 1,589
  • 6
  • 23
  • 47

3 Answers3

2

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

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • The main question is which flavor OP is using. Because the non-word-boundary character catches `[^a-zA-Z0-9_]` (aka `[^\w]`) in some Regex flavors so your first example may occasionally not succeed with Javascript Regexp, as an example (consider "testç"). – inhan Jan 08 '13 at 13:28
  • Thanks! i've choosen the first one. i assume that strings contains only letters(a-z). – Sylnois Jan 08 '13 at 13:52
1

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.

davidrac
  • 10,723
  • 3
  • 39
  • 71
0

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • `/test(.)/` would also work, no? Also, you probably want the leading `^` to mirror the OP's question. – broofa Jan 08 '13 at 13:41
  • @broofa: `/test(.+)/` should work, but that will break at newline characters. the `^` is not required in my regex. (See my examples) – Cerbrus Jan 08 '13 at 13:42