Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have been trying to write a regular expression in Java,but not been able to get the desired outputs.

My Regex requirement is to search a keyword in the file which can be :

5face
7face
$face
%face
face
faces
face's
faces'
face'
face4
face$
face <--Space after face

but it shall not read

duckface
duckface1
duckface$
facebook
facebook
3facebook
&facebook


and so on...

My Regex attempts have not been working great so far..

Can anyone please suggest something. Thank you.
Posted
Comments
Sergey Alexandrovich Kryukov 22-Feb-12 21:45pm    
"Not been able to get the desired outputs" is not informative. How about a code sample? What's the problem?
--SA
newbie.cppcoder 22-Feb-12 21:46pm    
the desired count for the keyword is not matching with my output. that is why i am checking regex

1 solution

The first thing to do is to write down exactly what you want to match. From your examples, it looks to me like this is a good start:
a non-letter
f
a
c
e
optional apostrophe
optional s
a non-letter

Translated into a regex, this turns into
[^a-zA-Z]face\'?s?[^a-zA-Z]

You then need to think about refinements. What about FACE Face faCE and so on? What if face is at the very beginning or end of the string you're scanning?
Then, what do you want to do with the results? Just count matches, list them in context, substitute for them, ...? For instance, my example includes (captures) the "before and after" non-letters, which may not be what you want if you're substituting. (It's easy to use non-capturing groups for these - just replace [^a-zA-Z] by (?:[^a-zA-Z]) in two places.)

If you're going to do anything serious with regexes, I strongly recommend downloading a copy of Expresso. It's free and brilliant.

Cheers,
Peter

[edit] fixed typos [/edit]
 
Share this answer
 
v2
Comments
ProEnggSoft 28-Mar-12 3:02am    
Very good answer and advice. +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900