• Post Reply Bookmark Topic Watch Topic
  • New Topic

Replace exact words using regular expressions  RSS feed

 
Pandu Rangam
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I have some text like
My Apartment, has Apartments where Apts is Apartment Aprartments @Apts. sdfasdfaApt Apt/No Aptasdf asdf Apts.. Apartments

from this i want replace all exact occurrences of
Apartment, Apartments, Apt, Apts,Apts., Apt/No with Some text, ex. "TEST".
After replacing text should look like this

My TEST, has TEST where TEST is TEST TEST @Apts. sdfasdfaApt TEST Aptasdf asdf TEST.
For this I need a regular expression.

Thanks in advance
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pandu Rangam:
Hi all,
I have some text like
My Apartment, has Apartments where Apts is Apartment Aprartments @Apts. sdfasdfaApt Apt/No Aptasdf asdf Apts.. Apartments

from this i want replace all exact occurrences of
Apartment, Apartments, Apt, Apts,Apts., Apt/No with Some text, ex. "TEST".
After replacing text should look like this

My TEST, has TEST where TEST is TEST TEST @Apts. sdfasdfaApt TEST Aptasdf asdf TEST.
For this I need a regular expression.

Thanks in advance


The regular expression is quite easy: just combine all words with |:
(Apartment)|(Apartments)|(Apt)|(Apts)|(Apts\\.)|(Apt/No)

Please notice the \\. In regular expressions . means any character, so you have to escape it with \. But because that's the Java escape character as well you have to escape that as well.
 
Pandu Rangam
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob Prime,

The regular expression is quite easy: just combine all words with |:
(Apartment)|(Apartments)|(Apt)|(Apts)|(Apts\\.)|(Apt/No)

I did in the same way but this will replace all occurance, I mean it will replace @Apts. and sdfasdfaApt. But I don't those words to change. I wrote code like this


out put is
My TEST, has TEST where TEST is TEST Aprartments @TEST sdfasdfaTEST TEST/No TESTasdf asdf TEST. TEST

Thanks in advance
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case you need to match a word boundary before and after the term. Have a look at "\b" for that.
 
Pandu Rangam
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ulf Dittmer,
Thanks for your suggestion. I changed the code accordingly


output is My TEST, has TEST where TEST is TEST TEST @TEST. sdfasdfaApt TEST/No Aptasdf asdf TEST.. TEST

it is failing for @Apts. and Apt/No.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!