Replace a string multiple times using regular expression
for example we have date May 12, 2010开发者_如何学Python
<cfset may_12_2010 = CreateDate(2010, 5, 12)>
using DateFormat
function, we can use
DateFormat(may_12_2010, "mmmm m dddd d yyyy")
which will show May 5 Wednesday 12 2010
if for some reason I can't use the DateFormat
function, how we can show the same results (with the same mask) with the above example?
code:
<cfset may_12_2010 = CreateDate(2010, 5, 12)>
<cfset mask = "mmmm m dddd d yyyy">
#DateFormat(may_12_2010, mask)#
<cfset d = DateFormat(may_12_2010, "d") />
<cfset dd = DateFormat(may_12_2010, "dd") />
<cfset ddd = DateFormat(may_12_2010, "ddd") />
<cfset dddd = DateFormat(may_12_2010, "dddd") />
<cfset m = DateFormat(may_12_2010, "m") />
<cfset mm = DateFormat(may_12_2010, "mm") />
<cfset mmm = DateFormat(may_12_2010, "mmm") />
<cfset mmmm = DateFormat(may_12_2010, "mmmm") />
<cfset yy = DateFormat(may_12_2010, "yy") />
<cfset yyyy = DateFormat(may_12_2010, "yyyy") />
<cfset stringDate = mask />
<cfset stringDate = REReplaceNoCase(stringDate, "d{4,4}", dddd, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "d{3,3}", ddd, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "d{2,2}", dd, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "d", d, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "m{4,4}", mmmm, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "m{3,3}", mmm, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "m{2,2}", mm, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "m", m, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "y{4,4}", yyyy, "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "y{2,2}", yy, "ALL") />
<br>
#stringDate#
the code above will show
May 5 Wednesday 12 2010
5ay 5 We12nes12ay 12 2010
thank you
To solve your problem, simply make your regexes:
<cfset stringDate = REReplaceNoCase(stringDate, "\bdddd\b" , dddd , "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "\bddd\b" , ddd , "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "\bdd\b" , dd , "ALL") />
<cfset stringDate = REReplaceNoCase(stringDate, "\bd\b" , d , "ALL") />
....
Where the \b
marks the position of a "word boundary" -- which is a change between a word character and non-word character, where a "word character" is [a-zA-Z0-9_]
-- and so prevents the d's in "wednesday" from matching.
But really, just use the DateFormat function properly!
I'm confused as why you can't use dateformat. I have never had dateformat not accept a value, you can even just use a string, it doesn't care.
精彩评论