0

Example text:

This is my car, I don't like it, because it is slow. This is my car, SomeRandom24324<>, it is slow. This is my car, how about you and me..., because it is slow.

I want to remove everything in between "This is" and "is slow".

I tried (?<=This is)(.*?)(?=is slow), but it only removes first occurrence and I get:

This isis slow. This is my car, SomeRandom24324<>, it is slow. This is my car, how about you and me..., because it is slow.

Rest of occurrences are still there.

As you understand I want to have only:

This isis slow. This isis slow. This isis slow.

PS: Any good book to learn regex?

5
  • You'll have to use the global flag. s/(?<=This is)(.*?)(?=is slow)//g should do it Commented Jan 2, 2015 at 21:43
  • C# dot net, more characters so i can comment. Commented Jan 2, 2015 at 21:43
  • Adam Smith I am trying in notepad++ for test, and it doesn't find it. Commented Jan 2, 2015 at 21:45
  • Works for me in Notepad++, exactly as written: (?<=This is)(.*?)(?=is slow) Commented Jan 2, 2015 at 21:51
  • regex101.com is a good test pad for regex Commented Jan 2, 2015 at 21:57

3 Answers 3

2

Your regular expression is fine. I would try enabling the dotall modifier to force the dot across newlines as well.

String result = Regex.Replace(input, @"(?s)(?<=This is).*?(?=is slow)", "");

As far as learning regular expressions, I would begin here: Regular-Expressions.infoRexEgg

Sign up to request clarification or add additional context in comments.

2 Comments

Here's a working demo which produces the correct result. ideone.com/guGJBs
basically in the code i had (?<=This is)(.*)(?=is slow) which gave me totally wrong result........... couldn't see it for 30 minutes, really? doh o_O
1

The regex is fine. You need to tell whatever you put that regex into (some replace call, probably) to replace all matches, not just one. That is not part of the regex, but a flag to the replacement instruction/call/whatever.

Comments

0

Doing this can depend on the language you are using. In perl I would use the substitute function which uses regexes, eg. $line=~ s/regex_with_2_groups/"$1 whatever-u-want $2"/g, but in java I might use String.replaceFirst() or String.replaceAll and in python re.sub(). An approach is to match '(2save1)toRemove(2save2)' and output "group1 whatever-u-want group2".

Great references are Mastering Regular Expressions and Regular Expressions Cookbook. See http://www.regular-expressions.info/ for regex deatails of all major languages that have them and software for testing and analyzing regexes and http://www.regexr.com/ has a free online tool for learning, building and testing regexes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.