1

For all the examples need 'a programming' as output

Example 1 : This is a programming test.
REGEX : a+\sprogramming -- Working

Example 2 : This is a test programming. This is a programming test
REGEX : a+\s(?!test)\sprogramming -- Working

Example 3 : This is a test programming. This is a basic a programming test
REGEX : a+\s(?!test)(.+)\sprogramming -- Not working

Actual O/P : a basic a programming
Expected O/P : a programming

That is, need 'a' printed only once.

Thanks in advance.

3
  • 1
    I've read this question three times and I still don't understand... Oct 30, 2012 at 6:29
  • If you only want one 'a', remove the + quantifier.
    – skunkfrukt
    Oct 30, 2012 at 6:30
  • 1
    why not simply /.*(a programming).*/ ? Oct 30, 2012 at 6:32

2 Answers 2

2

Is this what you are looking for?

REGEX : .*(a programming).*

O/p expected:

1.9.3p194 :001 > "This is a test programming. This is a basic a programming test ".match(/.*(a programming).*/)
 => #<MatchData "This is a test programming. This is a basic a programming test " 1:"a programming"> 
1.9.3p194 :002 > "This is a programming test. ".match(/.*(a programming).*/) => #<MatchData "This is a programming test. " 1:"a programming"> 
1.9.3p194 :003 > "This is a test programming. This is a programming test ".match(/.*(a programming).*/)
 => #<MatchData "This is a test programming. This is a programming test " 1:"a programming"> 
0

I'm not sure I understand your question.

If you're looking to match a word between two words, such as "a" and "test", then you do this:

a\s+(\S+)\s+test

(The \S with a capital "S" matches non-whitespace characters.)

If you want only the last such instance, then:

a\s+(\S+)\s+test(?!.*a\s+(\S+)\s+test)

(Notice what's inside the negative lookahead assertion is a copy of the part outside.)

In addition, you would want to use word boundaries, e.g.

\ba\s+(\S+)\s+test\b(?!.*\ba\s+(\S+)\s+test\b)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.