Message Boards Message Boards

2 Replies
0 Total Likes
View groups...
Share this post:

StringReplace help?

Posted 10 years ago


I have a list of strings and I want to replace several substrings in it. For example, take "A CO IN", I want to end up with only "A". I'm using

StringReplace["A CO IN",{Whitespace~~"IN"~~(Whitespace|EndOfString)->" ",Whitespace~~"CO"~~(Whitespace|EndOfString)->" "}]

The problem I have is that I'm ending up with "A IN", I checked the documentation and it is because after replacing the first pattern, it continues searching at the next character after the pattern. Therefore Whitespace~~"IN"~~(Whitespace|EndOfString) will never be matched because it continues searching at "I" after replacing " CO ". Can you help me accomplish my task?

POSTED BY: Miguel Olivo-V
2 Replies

One way is to use FixedPoint with a pure function as in:

 StringReplace[#, {Whitespace ~~ "IN" ~~ (Whitespace | EndOfString) ->
      " ", Whitespace ~~ "CO" ~~ (Whitespace | EndOfString) -> 
     " "}] &, "A CO IN"]
POSTED BY: David Reiss
Posted 10 years ago

Thanks a lot. Excellent answer as always, David.

POSTED BY: Miguel Olivo-V
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract