Message Boards Message Boards

0
|
4760 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Selectively replace strings in parentheses?

Posted 8 years ago

Hello everyone,

I have a string that has two substrings in parentheses. The string also contains a state abbreviation and zip code outside of the parentheses and another inside one of the parentheses. It looks like this:

myString = "Some words here, then (the quick brown fox) Los Angeles, CA 90071, and followed by (his other residence Chicago, IL 60604 right here)"

In strings such as this I want to remove the parenthesis that contains the state abbreviation and zip code and keep only the zip code. The result should be

myNewString = "Some words here, then (the quick brown fox) Los Angeles, CA 90071, and followed by Chicago, IL 60604"

I have a list of state abbreviations and have used Repeated[DigitCharacter,{5}] for the zip code, but my attempts with StringReplace, using Shortest and Overlaps in various combinations, do not give me what I want because the state abbreviation and zip code outside the parenthesis, CA 90071, keeps messing things up. Any tips?

Gregory

POSTED BY: Gregory Lypny
2 Replies
Posted 8 years ago

Hi Christopher,

Nicely done! Thank you. I did try throwing in the right parenthesis as an exception but I did not follow it with RepeatedNull. Never would have thought of that. Lots to learn.

Thanks again,

Gregory

POSTED BY: Gregory Lypny

Include ")" in an exception, to prevent overlaps.

res = StringReplace[myString,
  Shortest["(" ~~ (lhs : Except[")"] ...) ~~
     city : Except[WhitespaceCharacter] .. ~~
     ", " ~~
     st : Repeated[LetterCharacter, {2}] ~~
     sp : Repeated[WhitespaceCharacter, {1}] ~~
     zp : Repeated[DigitCharacter, {5}] ~~
     rhs___ ~~ ")"] :> city <> ", " <> st <> " " <> zp]

"Some words here, then (the quick brown fox) Los Angeles, CA 90071, and followed by Chicago, IL 60604"

myNewString === res
True
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract