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$
4
  • $\begingroup$ Try StringReplace[str, WordBoundary ~~ x : DigitCharacter .. ~~ WordBoundary :> x <> "/1"]. $\endgroup$ Commented Jul 22, 2015 at 10:00
  • $\begingroup$ @Guesswhoitis answer? $\endgroup$
    – Yves Klett
    Commented Jul 22, 2015 at 10:14
  • $\begingroup$ @YvesKlett It doesn't quite work as written. $\endgroup$
    – Mr.Wizard
    Commented Jul 22, 2015 at 10:31
  • 1
    $\begingroup$ @Mr. Wizard, dang, so close… :) $\endgroup$ Commented Jul 22, 2015 at 11:24

1 Answer 1

5
$\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 and acknowledge you have read our privacy policy.

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