Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to replace all "Nx" with "N0x" in the following, but I can't seem to figure it out.

data = {"N1 G01 X35 Y51 Z00", "N2 G01 X34 Y50 Z00", "N3 G01 X33 Y50 Z00", 
"N4 G01 X32 Y50 Z00", "N5 G01 X31 Y50 Z00", "N6 G01 X30 Y50 Z00", "N7 
G01 X29 Y50 Z00", "N8 G01 X28 Y50 Z00", "N9 G01 X27 Y50 Z00", "N10 
N00 G98 X00 Y00 Z-30", "N11 G01 X26 Y49 Z00", "N12 G01 X25 Y49 Z00", 
"N13 G01 X24 Y49 Z00"}

So far, I have tried several combinations of Regular Expressions and StringReplace, to no avail.

share|improve this question
3  
Why not StringReplace[#, "N" -> "N0"] & /@ data? – corey979 yesterday
    
I only need to insert the 0 after N's that have a single integer following it. :) – Janus Syrak yesterday
3  
(StringReplace[#, "N" ~~ d : DigitCharacter ~~ WordBoundary :> "N0" <> d]) & /@ data – alancalvitti yesterday

The following is a string expression which I think does what you describe:

StringReplace[data, 
  "N" ~~ d : DigitCharacter ~~ x : Except[DigitCharacter] :> 
  "N0" <> d <> x]

Note that StringReplace does automatically map onto lists of strings (which is documented), so you don't need to Map it onto the list of strings data.

If you prefer regular expressions here is the same expressed with regular expressions:

StringReplace[data, RegularExpression["N(\\d)([^\\d])"] :> "N0$1$2"]

These do both work for your example data, but won't replace when the pattern is at the end of a string, like in "N1 N2 G01 X35 Y51 N3", if you want to also handle those, that can be either achieved with an additional rule:

StringReplace[data, {
  "N" ~~ d : DigitCharacter ~~ x : Except[DigitCharacter] :> 
  "N0" <> d <> x,
  "N" ~~ d : DigitCharacter ~~ EndOfString :> "N0" <> d
}]

StringReplace[data, {
  RegularExpression["N(\\d)([^\\d])"] :> "N0$1$2",
  RegularExpression["N(\\d)$"] :> "N0$1"
}]

or with a slightly more complicated pattern:

StringReplace[data, 
  "N" ~~ d:DigitCharacter ~~ x:(Except[DigitCharacter] | EndOfString) :> 
  "N0" <> d <> x]

StringReplace[data,RegularExpression["N(\\d)([^\\d]|$)"] :> "N0$1$2"]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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