Message Boards Message Boards

0
|
7757 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How can I delete unwanted leading and trailing characters from a string

Posted 9 years ago

Hi everyone, I'm having a mental block. Say I have the following string:

myString = " % $ ,,- , the cat in the hat ---- , - # ,  "

and I want to pull out the the cat in the hat. How can I do that? I've tried StringReplace with various combinations of WordBoundary and LetterCharacter but I can seem to get it right.

Gregory

POSTED BY: Gregory Lypny
3 Replies
Posted 9 years ago

Hi Bill and I van, Thanks for your tips. Both work. I came up with something similar to yours, I van,

First[StringCases[myString, WordCharacter .. ~~ (WordCharacter | Whitespace) .. ~~ WordCharacter]

The only extra thing that StringCases requires over StringReplace is that the extracted string be pulled out of the list, as I have done using First.

POSTED BY: Gregory Lypny
StringCases[myString, WordCharacter ~~ (WordCharacter | " ") .. ~~ WordCharacter]

{"the cat in the hat"}

POSTED BY: l van Veen
Posted 9 years ago

Is this acceptable

StringReplace[myString, {RegularExpression["^\\W*t"] -> "t", RegularExpression["t\\W*$"] -> "t"}]
POSTED BY: Bill Simpson
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