reset password
Author Message
dbravoru
Posts: 60
Posted 17:01 Oct 22, 2014 |

I'm having trouble figuring out which regular expression to use. We're supposed to use regular expressions to match how many times a certain word appears in a text with along with certain other requirements.

I don't think I'm using the operands correctly.

To match words that contain apostrophes that are not their first or last characters, i tried using "[\']" just to make sure it would could count ALL of the apostrophes; this would count all of the apostrophes in the text, but the JUnit test says it counted 0 instances.

What am I doing wrong?

HeroVega
Posts: 8
Posted 19:31 Oct 22, 2014 |

Well first of all you have to remember that [] are for patterns, so ['] would only match " ' " (a single apostrophe) because that's what you said the pattern was. Also, you don't need to add the backslash to ' only for things that already have 1 backslash like "\d" since the extra backslash is to escape the previous one.

 

His wording is a little tricky, and it actually took me a while to figure it out too, but he want's words that contain apostrophes in the middle of the word (middle meaning after the first character and before the last) so "don't" would be a match.

However, and this was the tricky part, it doesn't mean that the word can't have the apostrophe at the beginning or the end. (I had to look at the output to actually figure this out) So you need to take that into account as well.

Without directly giving you the answer just remember these things:

  • The brackets are for patterns [A-z] etc but if you need more than one of those you need to add {1,n} (n being a number) or {1,} (meaning one or more)
  • Apostrophes don't need the \
  • The word CAN have apostrophes at the end, or at the beginning AS LONG AS IT ALSO has one in the middle

Make your pattern so it matches that and you'll get the right amount.

I deal with regex a bit but it always gets on my nerves, so I usually create another test class where I create a string of what I want to match, in this case words like "don't", and I print out if my regex matches my test string. I keep editing it until it says true or "does match" or whatever you want to have it print out, and then copy your regex and try it with the lab assignment.

(Hint: look at the sanitized output if you need to so you can see what you need to match)

Sorry if I rambled or confused you even more haha.