4
$\begingroup$

I have list of strings that I need to replace the last two characters. I am using RegularExpression to distinguish between "A1" and "A15". The problem that I am having is that when I try to replace the string found by the RegularExpression it returns the whole right hand side.

var = {"exampleA1","exampleA15"}

StringReplace[var, RegularExpression["A\\w+"] -> {"A1" -> "foo", "A15" -> "cat"}]

{"example" ~~ {"A1" -> "foo", "A15" -> "cat"}, "example" ~~ {"A1" -> "foo", "A15" -> "cat"}, "example" ~~ {"A1" -> "foo", "A15" -> "cat"}, "example" ~~ {"A1" -> "foo", "A15" -> "cat"}}

$\endgroup$
6
$\begingroup$

If you want "A" followed by digits then you should be using \d+ instead of \w+. However that is not the real issue.

With

var = {"exampleA1", "exampleA15"};
rep = {"A1" -> "foo", "A15" -> "cat"};

Then

StringReplace[var, a : ("A" ~~ DigitCharacter ..) ~~ EndOfString :> (a /. rep)]

or

StringReplace[var, a : RegularExpression["A\\d+$"] :> (a /. rep)]

gives

{"examplefoo", "examplecat"}

EndOfString ($ in Regex) is not strictly needed in this case but it will make a difference if the pattern could occur elsewhere in the string.

Hope this helps.

$\endgroup$
3
$\begingroup$

Slightly cheating:

StringReplace[#, {"A15" -> "cat", "A1" -> "foo"}] & /@ var

{"examplefoo", "examplecat"}

i.e. the "Anumber" must be in descending order, like {"A16", "A8", "A5"}, but not {"A16", "A5", "A8"}.

$\endgroup$
  • 2
    $\begingroup$ It is sufficient to write StringReplace[var, {"A15" -> "cat", "A1" -> "foo"}] (the use of /@ is unnecessary). $\endgroup$ – WReach Oct 10 '16 at 0:12
3
$\begingroup$

You can use \[RuleDelayed] symbol, :> to apply a function to your expression. In this case, you want to apply additional rules to the pattern you find, I use ReplaceAll symbol, /. in the below answer.

StringReplace[var, a : RegularExpression["A\\w+"] :> (a /. {"A1" -> "foo", 
   "A15" -> "cat"})]

{"exampleA1", "exampleA15"}

In your example, your entire regex gets replaced by {"A1" -> "foo", "A15" -> "cat"} which isn't a string so you see the StringExpression operators in your result ~~

EDIT

Added some missing syntax () to the answer

$\endgroup$
  • 2
    $\begingroup$ Thanks for the help, But it still isn't replacing A1 and A15 with "foo" and "cat", respectively. $\endgroup$ – Paul Oct 9 '16 at 22:38
  • 2
    $\begingroup$ Add parentheses around the right-hand side: StringReplace[var, a : RegularExpression[ "A\\w+"] :> (a /. {"A1" -> "foo", "A15" -> "cat"})] $\endgroup$ – WReach Oct 10 '16 at 0:10
  • $\begingroup$ @Paul sorry about that @ WReach noticed I was missing some parentheses $\endgroup$ – Peter Roberge Oct 10 '16 at 3:06
  • $\begingroup$ No problem and thanks for the help $\endgroup$ – Paul Oct 10 '16 at 11:41

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.