Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Operations on RegularExpression matches

  • To: mathgroup at smc.vnet.net
  • Subject: [mg120001] Re: Operations on RegularExpression matches
  • From: Albert Retey <awnl at gmx-topmail.de>
  • Date: Tue, 5 Jul 2011 05:09:23 -0400 (EDT)
  • References: <ius5nq$2g4$1@smc.vnet.net>

Hi,
>
> I have string of all lower case letters:
>
> 	string = "this is a string"
>
> I wish to capitalize the first letter:
>
> 	StringReplace[string, StartOfString ~~ x_ ->  ToUpperCase[x]]  (* Does want I want *)
>
> Now I try to do the same thing using RegularExpression:
>
> 	StringReplace[string, RegularExpression["(^.)"] ->  ToUpperCase["$1"]]
>
> which fails (returns original string without capitalization).
>
> I know the match is occurring since
>
> 	StringReplace[string, RegularExpression["(^.)"] ->  ToUpperCase["$1X"]]
>
> returns
>
> 	"tXhis is a string"
>
> What am I missing about using the matched part of a regular expression?

the problem is that ToUpperCase is done on the pattern, not the match. 
You need RuleDelayed so that ToUpperCase is done on the matching string:

StringReplace[string, RegularExpression["(^.)"] :> ToUpperCase["$1"]]

this is not necessary with the StringExpression approach since then 
ToUpperCase[x] remains unevaluated since x is no string.

hth,

albert


  • Prev by Date: Re: Operations on RegularExpression matches
  • Next by Date: Re: Insoluble marbles-in-urn problem?
  • Previous by thread: Re: Operations on RegularExpression matches
  • Next by thread: Numerical accuracy/precision - this is a bug or a feature?