3
$\begingroup$

I would like to find all occurrences of a full stop "." followed by a capital letter in a string and have these replaced with a "; ". How do I do this in Mathematica?

e.g. string="this is a test.A new sentence here" -> output

"this is a test; A new sentence here"

Edit: and also one other pattern matching question - in a string I would like to have every other line occuring before a next line (\n) being deleted - how do I do that one?

e.g.

string="this line should be deleted\nthis one not\nbut this one should be deleted too\nthis one not"

-> output

"this one not\nthis one not"
$\endgroup$

2 Answers 2

6
$\begingroup$

Some variety:

StringReplace[string, ("." ~~ char : LetterCharacter /;UpperCaseQ[char]) :> "; " <> char]

"this is a test; A new sentence here"

As for your second question, one way to go about it would be:

StringJoin[Riffle[StringSplit[string, "\n"][[2 ;; -1 ;; 2]], "\n"]]
"this one not
 this one not"
FullForm[%]
"this one not\nthis one not"
$\endgroup$
3
  • $\begingroup$ Thanks a lot, and also for the other answer! $\endgroup$ Commented Nov 18, 2013 at 13:12
  • $\begingroup$ Oh yes and would you also happen to know the answer to the other question I put in my edited post? $\endgroup$ Commented Nov 18, 2013 at 13:19
  • $\begingroup$ @TomWenseleers it will be better to ask separate question. $\endgroup$
    – Kuba
    Commented Nov 18, 2013 at 13:31
5
$\begingroup$
StringReplace["this is a test.A new sentence here", RegularExpression["\\.([A-Z])"] -> "; $1"]

The $1 is needed to carry the capital letter into the returned string or it will be lost.

$\endgroup$
3
  • 4
    $\begingroup$ Hey, $1 per replacement can get expensive quickly! $\endgroup$
    – Yves Klett
    Commented Nov 18, 2013 at 12:26
  • 1
    $\begingroup$ Its a penalty designed to encourage correct punctuation in the first place. $\endgroup$
    – Ymareth
    Commented Nov 18, 2013 at 12:59
  • $\begingroup$ Talk about cost functions, eh? $\endgroup$
    – Yves Klett
    Commented Nov 18, 2013 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.