• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

exact word match

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I have a requirement where I have to avoid a particular word in a sentence. Example-
word to avoid= "head"
I don't want this word to be in the string. If I use indexOf() or contains() method, it also checks for headfirst or forehead, but this should be allowed. And if I use indexOf(" head ") or contains(" head "), then it will not check if I add only head as a word in string or if I write "head." i.e '.' after head. or if I use it with any special characters.

I think regular expression will help. But I haven't used regular expressions. Would be helpful if anyone can throw some light on this or better post the code snippet for the same.
 
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A regular expression is just going to help you keep a certain pattern, or look for a certain pattern in a string.

If you know that you're looking for 'head', just do a loop and while string.indexOf('head') > -1, replace that occurance of 'head' with "".

so:



That should do it!

Justin
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well \b is a word boundry in regular expression



The above will fail on punctuation so you would have to account for that.

This is the basic idea:



Eric
 
Something must be done about this. Let's start by reading this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic