coldfusion - remove specific text from string - coldfusion

I am looking to remove "pharmacy" from an input field before I enter the text into the database.
Example - "Ciaran pharmacy" will show as "Ciaran".

Your requirements are pretty simple:
<cfscript>
name = "Ciaran pharmacy";
newName = replace(name, 'pharmacy', '');
</cfscript>
I suspect there's more complication to it than that.
Is it only if 'pharmacy' is the last word?
Is it always just the last word in the name?
Or is it always 'pharmacy' regardless of where it is in the string?
If it's the 3rd case, specify the 'ALL' parameter:
newName = replace(name, 'pharmacy', '', 'ALL');

You can also use REReplace to remove multiple occurances of the string. And TRIM function to remove the spaces before and after.
<cfoutput>
#TRIM(REReplace("pharmacy in Ciaran pharmacy", "pharmacy", "","ALL"))#
</cfoutput>

local.replaceContent = replace('My Name is developer', 'My', 'I','ALL');
writeDump(local.replaceContent);
abort;
Result

Related

Using a regex to extract a substring

I have the following string:
<cfset foo="Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124 Course Date/Time: February 03, 2017">
I want to use a regex to extract only the list of students which is:
Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam
If I use replace, I have to use many replace to make it happen. I think it would work with one regex, but I am not good with regular expressions. Can anybody help and guide?
Please pay no attention to the insult someone made in the comments. That's not what SO is for.
Anywho, there are a number of ColdFusion string functions that make your job easier. Here's what I did. This is assuming certain parts of your string will always be the same.
May not be super efficient, but it will help detail step by step what we're doing, and gives you precise control.
<cfset StringVar = "Students: Am Goron, rika Mrks, Apl Rirez, Ktsana Tanam Course Location: Training Center - Hillsboro, OR - Hillsboro OR 97124 Course Date/Time: February 03, 2017">
<!---Set total length of string --->
<cfset LengthIndent = len(StringVar)>
<!---Trim off the Students: part--->
<cfset StringVar = Right(StringVar,LengthIndent-9)>
<!---Trim up to the Course Location: part--->
<cfset StringVar = SpanExcluding(StringVar, ":")>
<!---Set total length of REMAINING string --->
<cfset LengthIndent = len(StringVar)>
<!---Trim off the Course Location: part--->
<cfset StringVar = LEFT(StringVar,LengthIndent-15)>
<!---Outputting this will give you ONLY names of students--->
<cfoutput>#StringVar#</cfoutput>
Regex's are not my strong suit either, but there are online tutorials and test sites like RegExrv2.1 you can use for practicing. With a bit of reading I came up with this:
<cfset list = reReplaceNoCase(text, "^Students:(.*?)Course Location:.*$", "\1", "all")>
Breaking it down, it searches for a string that:
^Students: - starts with "Students:"
(.+?) - followed by one or more characters as a capturing group
Course Location: - followed by the course location
.*$ - ending with zero or more characters
Then use a backreference, i.e. \1 to replace everything except the matched group, ie the student list.
If you prefer non-regex options, you could also cheat (a little) and insert an extra colon, ie : before course location. That would allow you to treat the string as a list delimited by colons, and extract the second element with list functions:
<cfset list = listGetAt( replace(text, "Course Location:", ":Course Location:"), 2, ":")>

Cutting a string in ColdFusion

I have values in my query that looks like the following:
Decrease with an active address (2) or Unsecured task (100) etc.
The value within the parentheses varies, it can be one, two, three digits or more because this is a count value.
I just need to get the description not the parentheses nor the value.
So what I need is just:
Decrease with an active address
Unsecured task
etc.
How can I get rid of the opening (, the numeric value and the closing )?
In ColdFusion 8?
As Dan mentioned in the comments, one option is using reReplace() with the appropriate expression to remove any text within parenthesis:
<cfscript>
origText = "Decrease with an active address (2)";
newText = reReplaceNoCase(origText, "\([^)]*\)", "", "all");
writeDump( newText );
</cfscript>
Update:
As Alex mentioned in the comments, if you just want to "cut" the string, and grab the part before the parenthesis, try something like this:
<cfscript>
origText = "Decrease with an active address (2) plus more text after the parenthesis";
newText = reReplaceNoCase(origText, "\([0-9]*\).*$", "", "all");
writeOutput("<br>"& newText );
</cfscript>

Find Multiple Occurrences in String using REFind

I'm trying to get ColdFusion's REFindNoCase function to return multiple instances of a matching string but can't seem to get it to work:
<cfset string2test="cfid skldfjskdl cfid sdlkfjslfjs cftoken dslkfjdslfjks cftoken">
<cfset CookieCheck = REFindNoCase( 'CFTOKEN', string2test, 1, true)>
<cfif arrayLen( CookieCheck['LEN'] ) gt 1>
MULTIPLE CFTOKEN!
</cfif>
Is there a regular expression magic syntax I need to use to make it search for more than 1?
The syntax of the code above will create structure with arrays (LEN,POS) for pattern match and subexpressions. RegEx subexpressions are within parenthesis in the pattern. The 'CFTOKEN' pattern does not contain a subexpression.
I don't think that REFindNoCase will do what you are wanting to accomplish.
For example, if you use '.*?(cftoken)' as the pattern:
<cfset CookieCheck = REFindNoCase('.*?(CFTOKEN)', string2test, 1, true)>
(CFTOKEN) is a subexpression. If you remove the "?", the information for the last occurrence of 'cftoken' is returned.
The values in the first array items will match the entire pattern up to the first 'cftoken' (the first 40 characters of the string). The second set of values will identify the 'cftoken' string that was found in first match (first 40 chars).
Because the statement in the example does not include subexpressions, only the first pattern match is returned.
If you need to check to see if something is listed multiple times or you don't need to manipulate the original string, I would recommend using REMatchNoCase(). It returns an array of pattern matches but without the position info.
You could create a custom method to loop over the string, and toss each occurrence into an array (or struct, or whatever you want). Here's an example of how I might approach it:
<cfscript>
public array function reFindMatches(required string regex, required string str) {
var start = 1;
var result = [];
var matches = [];
var match = '';
do {
matches = ReFind(arguments.regex, arguments.str, start, true);
if ( matches.pos[1] ) {
match = matches.len[1] ? Mid(arguments.str, matches.pos[1], matches.len[1]) : '';
ArrayAppend(result, match);
start = matches.pos[1] + matches.len[1];
}
} while(matches.pos[1]);
return result;
}
testString = 'cfid skldfjskdl cfid sdlkfjslfjs cftoken dslkfjdslfjks cftoken';
regex = '(?i)(\bcftoken\b)';
check = reFindMatches(regex=regex, str=testString);
WriteDump(var=check);
</cfscript>
The sample regex I've included begins with (?i) which indicates that the search is case insensitive. So, it's not necessary to call ReFindNoCase ... you can simply pass in whatever regex you wish to use.
The code above should output an array with two elements containing the word cftoken.
If you need to count how many instances there are, use rematch (or rematchNoCase).
If all you need is to identify if there's more than one, you can do this:
<cfset FirstInstance = refindNoCase( 'cftoken' , string2test ) />
<cfif FirstInstance AND refindNoCase( 'cftoken' , string2test , FirstInstance+7 ) >
... more than one instance ...
</cfif>
Which is probably more efficient than rematch, using sub-expressions or looping multiple times.
Depending on the data concerned, it might be even more efficient to do something like:
<bfif string2text.indexOf('cftoken') NEQ string2text.lastIndexOf('cftoken') >
(i.e. if you know that an additional instances would always near the end of the string, whilst initial ones are not.)

Getting string between two characters - Coldfusion

I'm struggling a bit with ColdFusion (not the language I ever write in).
I am trying to do a regex to get a part of a string.
So for example, if my string is: D_CECILA23_CEC23423
I want the part that is between the 2 underscores.
This is the code I have so far, and it works for anything that is alpha characters, but when a number is thrown into the mix, it just breaks.
<cfset myStr = "D_CELCI_LISA">
<cfset myStr2 = reReplace(myStr, "([\w\d\%]+)(\_)([/ A-Z]+)(\_)([\w\d\?]+)", "\3", "all") >
<cfoutput>
myStr: #myStr#<br />
myStr2: #myStr2#<br />
</cfoutput>
Which gives me:
myStr: D_CELCI_LISA
myStr2: CELCI
If it really is as simple as getting the text between the first and second underscore character, you don't need a regex. This'll do it:
myStr2 = listGetAt(myStr, 2, "_");
That said, this should do for the regex in that context: ^.*_([^_]+)_.*$, eg:
myStr2 = reReplace(myStr, "^.*_([^_]+)_.*$", "\1", "all");
#user2429578 ListLast() and ListFirst() for the last or first element of a list.

Regex to find length in description

<cfset RegexToFindLength = "Length:.*?(\d*\.?\d+)\s*(""|")"/>
<cfset Description = "blah blah blah 2.5"""/>
<cfset size = #reMatch(RegexToFindLength, Description)# />
<cfdump var="#size#">
Error Message: ColdFusion was looking at the following text:
)
looking to extract Length: 2.5" from the products description.
I have tested the above regex expression in regexpal and it works. But when i try using it in a cfm page, i get errors.
Can someone explain to me how this would be setup in CF?
You have a few issues here.
1) You don't escape your double quotes, so you end up closing your regex string and confusing it.
Personally, when I have to use double quotes in a string, I tend to use single quotes to define the string if I can.
<cfset RegexToFindLength = 'Length:.*?(\d*\.?\d+)\s*(""|")'/>
2) Your Description variable doesn't have the string you're searching for, so there will be no match. I changed this to the following to make it work (note the single quotes for defining the string):
<cfset Description = 'Length:.:2.5""'/>
3) (maybe not an issue) Size is not being set to a number. rematch returns an array of strings. You'll want to check the length of the string inside the array positions or check the length of the array itself - I don't know what exactly it is that you want to do.