I'd like to replace the first two digit and replace it with 0
In case it start with 0 then nothing need to be changed.
Example: 445656 to 056....
<cfif number (BEGIN WITH?) "44">
<cfset number = Right(number , Len(number )-2) />
But this just will remove the first two digits. thank you for the support
It looks like you're keeping your numbers that "start with 0" as strings. Try this:
<!--- // a number that does not start with zero --->
<cfset theNumber = "445656" />
<cfset theNumber = left(theNumber, 1) is 0 ? theNumber : REReplaceNoCase(theNumber, "^[0-9]{2}", 0) />
<!--- // returns 05656 --->
<cfoutput>#theNumber#</cfoutput>
<hr />
<!--- // a number that starts with zero --->
<cfset theNumber = "05656" />
<cfset theNumber = left(theNumber, 1) is 0 ? theNumber : REReplaceNoCase(theNumber, "^[0-9]{2}", 0) />
<!--- // returns 05656 --->
<cfoutput>#theNumber#</cfoutput>
If your number always starts with either 0 or 44 you can use
<cfset theNumber = left(theNumber, 1) is 0
? theNumber
: REReplaceNoCase(theNumber, "^[4]{2}", 0) />
Update:
Also, read the comments, there are some good points in there.
This reReplace() can be run on any string, will only modify and replace with 0 if the string starts with 44.
<cfscript>
phoneNumber = "44556677";
phoneNumber = reReplace(phoneNumber, "^44", "0");
writeOutput(phoneNumber);
</cfscript>
Related
Is there an easier/shorter way to convert the final comma of a currency input to a decimal.
Inputs look like 2 000,99 OR 2,000,99
MySQL wants them to look like 2000.99
<cfform action="commatest.cfm?gotime" onsubmit="commatest.cfm" method="post" name="waiv">
<cfinput type="text" name="commer">
<input type="submit" style="width:180px;" value="convertme" class="hide button">
</cfform>
<cfif isdefined("gotime")>
<!--- START SCRIPT --->
<cfset formentry = FORM.commer>
<cfset howlong = #len(formentry)#>
<cfif howlong GT 3>
<cfset leftlen = howlong - 3>
<cfset rside = #right(formentry, 3)#>
<cfset rside = ReReplace(rside,"[,]",".", "ALL")>
<cfset lside = #left(FORM.commer, leftlen)#>
<cfset lside = ReReplaceNoCase(lside,"[-$A-Z,]","", "ALL")>
<cfset lside = reReplace(lside, "[[:space:]]", "", "ALL") />
<cfset newb = #lside# & #rside#>
<!--- OUTPUT TO DATABASE (or webpage in this case) --->
<cfoutput>
<h1>#newb# (number? #IsNumeric(newb)#)</h1>
</cfoutput>
<cfelse>
<cfoutput>
<h1>#formentry# (number? #IsNumeric(formentry)#)</h1>
</cfoutput>
</cfif>
</cfif>
As usual there are several different ways to do this. I would probably do something like this:
<cfscript>
source1 = '2 000,99';
source2 = '2,000,99';
// remove ALL commas and spaces
example1 = REReplace(source1,"[\s,]","","all");
example2 = REReplace(source2,"[\s,]","","all");
// insert a decimal before the last two digits
example1 = Insert(".",example1,(Len(example1)-2));
example2 = Insert(".",example2,(Len(example2)-2));
writeOutput(source1 & " = " & example1);
writeOutput("<br>");
writeOutput(source2 & " = " & example2);
</cfscript>
That code gives the following output:
2 000,99 = 2000.99
2,000,99 = 2000.99
Of course this assumes that the last two digits are always going to be after the decimal point.
Here is a gist of the code above.
Please have a look at the code block below:
<cfset index = 0 />
<cfloop collection="#anotherPerson#" item="key" >
<cfset index = index+1 />
<cfoutput>
#key# : #anotherPerson[key]#
<cfif index lt ArrayLen(structKeyArray(anotherPerson))> , </cfif>
</cfoutput>
</cfloop>
<!--- Result
age : 24 , haar : Blondes haar , sex : female , ort : Hanau
---->
Now can you please tell me how could I achieve the same result without setting an index outside and incrementing it inside the loop? If you notice carefully, I had to write two more cfset tag and one cfif tag with expensive code just to avoid a comma (,) at the end of the collection!
Ok, I'm showing you two answers. The first will run on ColdFusion 9. Since other people might find this thread and be using Lucee Server or a newer version of Adobe ColdFusion, I'm including a one-liner that uses higher order functions and runs on ACF 2016. There's a lot of syntactic sugar (like member functions) and functional programming you're missing by being on CF9. These answers use script, because manipulating data is not something for a view (where tags/templating are used).
Set up the data
myStruct = { 'age'=24, 'haar'='Blondes haar', 'sex'='female', 'ort'='Hanau' };
CF9 compat, convert data to array and use delimiter to add commas
myArray = [];
for( key in myStruct ) {
arrayAppend( myArray, key & ' : ' & myStruct[ key ] );
}
writeOutput( arrayToList( myArray, ', ' ) );
Modern CFML. Use struct reduction closure to convert each key into an aggregated array which is then turned into a list.
writeOutput( myStruct.reduce( function(r,k,v,s){ return r.append( k & ' : ' & s[ k ] ); }, [] ).toList( ', ' ) );
http://cfdocs.org/structreduce
Some friends provided two different solutions. Both are efficient and elegant!
Solution 1
<cfset isFirst = true />
<cfloop collection="#anotherPerson#" item="key" >
<cfif isFirst>
<cfset isFirst = false />
<cfelse>
,
</cfif>
<cfoutput>
#key# : #anotherPerson[key]#
</cfoutput>
</cfloop>
Solution 2
<cfset resultList = "" />
<cfloop collection="#anotherPerson#" item="key" >
<cfset resultList = ListAppend(resultList, "#key# : #anotherPerson[key]#" ) />
</cfloop>
Cheers!
Just trim the comma when you are done, no skip logic required.
<cfset html = '' />
<cfloop collection="#anotherPerson#" item="key" >
<cfset html &= "#key# : #anotherPerson[key]# , " />
</cfloop>
<cfset html = left(html,len(html)-3) />
<cfoutput>#html#</cfoutput>
Readable, simple, works.
I have a spreadsheet query bringing back results. Negative numbers are formatted as ([$$123.12]) and positive numbers are formatted as ("$$123.12").
I need to format the negative number as -123.12 and the positive number as 123.12 before being inserted into a db. What type of regex would I need to use to do that? Or, could I use ColdFusion's Replace() function..and, if so, how?
We created xList as holder for the variable to simulate a looping query.
Assuming negative numbers will always contain "[" and positive numbers don't have the brackets we will loop on the list and check for "[" to format the negative numbers and then format the positive numbers for values not having brackets.
<cfset xlist = '([$$123.12]),("$$123.12")'>
<cfloop list="#xlist#" index="x">
<cfif FindNoCase("[", x )>
<cfset xVal = "-" & rereplaceNoCase(x,"[^0-9.]","","all" )>
<cfelse>
<cfset xVal = rereplaceNoCase(x,"[^0-9.]","","all" )>
</cfif>
<cfdump var="#xVal#"><br>
</cfloop>
Here's a slightly modified version of when I did something similar. Basically, I'm treating the bracket as a negative sign, and stripping out other irrelevant characters, like $. I wasn't clear on whether or not the parenthesis were part of your answer, in which case those would need to be stripped out, too.
<cffunction name="launderMoney">
<cfargument name="value">
<cfset var multiplier = 1>
<cfset arguments.value = Replace(trim(arguments.value), '"', "", "all")>
<cfif Find("[", arguments.value)>
<cfset multiplier = -1>
<cfset arguments.value = Replace(Replace(arguments.value, "[", "", "all"), "]", "", "all")>
</cfif>
<cfset var temp = Trim(Replace(Replace(trim(arguments.value), "$", "", "all"), ",", "", "all"))>
<cfif isNumeric(temp)>
<cfset temp *= multiplier>
</cfif>
<cfreturn temp>
</cffunction>
<p>#LaunderMoney('"$$123.12"')#</p>
<p>#LaunderMoney('[$$123.12]')#</p>
I need to display an output from a data record that is formatted similar to this: XXXX:12345 (Xxxxxxxxx)
However, the only data I want to output is the "12345" and with two preceding zeros, i.e. the output should look like "0012345". The "12345" in the record is example only, each record has a unique number assigned. An example record looks like this: CAST:98765 (RPOS1234-XY)
Can I use the ReplaceNoCase() to pull only that data out of the record? If so, how would I write the code to remove the unwanted characters?
You can do this in one line of code using a few functions.
str = 'CAST:98765 (RPOS1234-XY)';
projectCode = '00' & listLast( listFirst( str, ' ' ), ':' );
writeDump( projectCode );
To explain this code from the inner most function going out.
ListFirst() gets the first element in an a list based on the delimiter you specify, in this case the delimiter is ' ' - a space - yes, you can use a space as a delimiter.
ListLast() gets the last element in a list based on the delimiter you specify, in this case the delimiter is ':'
The first part simplt appends '00' to the result of the above function calls.
If I had to use reReplaceNoCase or reFindNoCase this is how I would do it.
function parseTokenUsingReFindNoCase(token) {
var local = {};
// use regex to locate position of number (see only set of parentheses in regex pattern)
local.positions = reFindNoCase("^.+:(\d+).+$", arguments.token, 1, true);
// obtain the token substring and ensure at least 7 digits with preceding 0's
local.result = numberFormat( mid(arguments.token, local.positions.pos[2], local.positions.len[2]), repeatString(0, 7));
return local.result;
}
function parseTokenUsingReReplaceNoCase(token) {
var local = {};
// use regex to strip away text before and after the token
local.result = reReplaceNoCase(arguments.token, "(^\D+|\s.+$)", "", "all");
// ensure at least 7 digits with preceding 0's
local.result = numberFormat(local.result, repeatString(0, 7));
return local.result;
}
<h1>ParseToken</h1>
<h2>Using ReFindNoCase</h2>
<cfdump var="#parseTokenUsingReFindNoCase("CAST:98765 (RPOS1234-XY)")#" /><br>
<cfdump var="#parseTokenUsingReFindNoCase("CAST:591498 (FUBAR56-XE)")#" /><br>
<cfdump var="#parseTokenUsingReFindNoCase("CAST:784 (RFP4542-LL)")#" /><br>
<h2>Using ReReplaceNoCase</h2>
<cfdump var="#parseTokenUsingReReplaceNoCase("CAST:98765 (RPOS1234-XY)")#" /><br>
<cfdump var="#parseTokenUsingReReplaceNoCase("CAST:591498 (FUBAR56-XE)")#" /><br>
<cfdump var="#parseTokenUsingReReplaceNoCase("CAST:784 (RFP4542-LL)")#" /><br>
ParseToken
Using ReFindNoCase
0098765
0591498
0000784
Using ReReplaceNoCase
0098765
0591498
0000784
It doesn't use replaceNoCase, but based on your comments this will work:
<cfset castTicket = projectCode>
<!--- strip the first 5 characters, since it is always "CAST " --->
<cfset castTicket = removechars(castTicket, 1,5)>
<!--- now return the leftmost characters, up to the space --->
<cfset castTicket = left(castTicket, find(" ", castTicket) )>
<!--- format the number so it has 7 digits (2 leading zeros in this case) --->
<cfset castTicket = NumberFormat(castTicket, 0000000)>
<cfoutput>#castTicket#</cfoutput>
Returns:
0012345
I've been cracking my head over this for quite some time.
I currently build a custom BB-Code function as part of a project at work. But I don't get it to work at one point: a [code] block.
Using ColdFusion regex, I want to replace the < and > characters with < and >, but only on HTML betweeen the [code] blocks.
So, how can I restrict a regex expression to the part of the string which is between the [code] blocks.
Thanks in advance for any help.
For those who stumble upon this question and could use an answer as well, I'll provide an example for parsing HTML in [code] blocks. Looks somewhat messy though:
<cfset contents = form.yourString />
<cfset substring1= "[code]" />
<cfset occurrences1 = ( Len(contents) - Len(Replace(contents,substring1,"","ALL"))) / Len(substring1) />
<cfset substring2= "[/code]" />
<cfset occurrences2 = ( Len(contents) - Len(Replace(contents,substring2,"","ALL"))) / Len(substring2) />
<cfif occurrences1 EQ occurrences2 AND occurrences1 GT 0 AND occurrences2 GT 0>
<cfset loopinstance = occurrences1 />
<cfelse>
<cfif occurrences1 LT occurrences2>
<cfset loopinstance = occurrences1 />
<cfelse>
<cfset loopinstance = occurrences2 />
</cfif>
</cfif>
<cfloop index="code_loop" from="1" to="#loopinstance#">
<cfscript>
// prepare variables //
code_string = contents;
startpos = FindNoCase("[code]", code_string);
startpos = Evaluate(startpos + 6); // adjust the correct position of string in question
endpos = FindNoCase("[/code]", code_string);
code_string = Mid(code_string, startpos, Evaluate(endpos - startpos)); // extract the string between code brackets
//** Replace-Codes are extensible depending on the used programming languages **//
code_string = ReplaceNoCase(code_string, "<","<", "ALL");
code_string = ReplaceNoCase(code_string, ">",">", "ALL");
//** process conversion of [code] block **//
startpos = FindNoCase("[code]", contents); // reevaluating the start and end positions for main string
startpos = Evaluate(startpos + 6); // adjust the correct position of form string
endpos = FindNoCase("[/code]", contents);
contents = RemoveChars(contents, startpos, Evaluate(endpos - startpos)); // remove the extracted string
contents = Insert(code_string, contents, Evaluate(startpos - 1)); // insert the processed code block to the original position
contents = ReplaceNoCase(contents, "[code]", "[coded]", "ONE"); // "flagging" the processed [code] block as finished by adding a "d"
contents = ReplaceNoCase(contents, "[/code]", "[/coded]", "ONE"); // "flagging" the processed [code] block as finished by adding a "d"
</cfscript>
</cfloop>
<!--- This is the regex to turn a written [code] block into an escaped HTML block --->
<cfscript>
contents = REReplaceNoCase(contents, "\[coded\](.*?)\[/coded\]", "<div id =""code_test"">Escaped Code: <br />\1</div>", "ALL");
</cfscript>
I hope this will help some people who have a hard time following #David Faber's help.
I think in ColdFusion you'll have to iterate over the string, searching for occurrences of "[code]". When you find such an occurrence, read in the string until you hit "[/code]". Take that string and do a replaceList to replace the characters. Use the removeChars and insert functions to replace the old string with the new. One problem with using regular expressions in this context is that the CF function REReplace can't replace a pattern with another pattern, only with a string.