Search code examples
javastringcontain

How to search for a string and similar word in a text?


I have to lookup for a word "age" and similar word in a text file.

I have following sentence :

  • 18 years of age
  • man aged 51
  • man ages between 25 to 50
  • between 5 to 75 years of age.(with dot)
  • between 5 to 75 years of age, (with comma)
  • agent name is xyz (agent contain age).

String.contains always return true in each case. My requirement is to pass the first five sentence and it return false in last case.

I will solve this problem by writing some code which contains a bunch of string " age ", " age." , "ages", "aged", " age," etc..

Is there any better way to solve this problem.


Solution

  • If you use regex, you have to put all the possiblities.

    string.matches("(?i).*\\bage[ds]?\\b.*");