3
$\begingroup$

Considering we have a string:

str = "1a 789 4/7 123/7 asff %$#7 478 9/4"

How can I insert "/1" for the numbers that are integers, to have the following result:

res = "1a 789/1 4/7 123/7 asff %$#7 478/1 9/4"

Thanks

$\endgroup$
  • $\begingroup$ Try StringReplace[str, WordBoundary ~~ x : DigitCharacter .. ~~ WordBoundary :> x <> "/1"]. $\endgroup$ – J. M. will be back soon Jul 22 '15 at 10:00
  • $\begingroup$ @Guesswhoitis answer? $\endgroup$ – Yves Klett Jul 22 '15 at 10:14
  • $\begingroup$ @YvesKlett It doesn't quite work as written. $\endgroup$ – Mr.Wizard Jul 22 '15 at 10:31
  • 1
    $\begingroup$ @Mr. Wizard, dang, so close… :) $\endgroup$ – J. M. will be back soon Jul 22 '15 at 11:24
4
$\begingroup$

If there is always one space at a time as shown, or if the number of spaces is irrelevant:

str = "1a 789 4/7 123/7 asff %$#7 478 9/4";

StringSplit[str] /. 
  s_String /; StringMatchQ[s, DigitCharacter ..] :> s <> "/1" // StringRiffle
"1a 789/1 4/7 123/7 asff %$#7 478/1 9/4"

Or adjusting J.M.'s comment code to work:

StringReplace[str, 
 w1 : Whitespace | StartOfString ~~ x : DigitCharacter .. ~~ 
   w2 : Whitespace | EndOfString :> w1 <> x <> "/1" <> w2]
"1a 789/1 4/7 123/7 asff %$#7 478/1 9/4"
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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