Reputation:
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?
Upvotes: 2
Views: 278
Reputation: 28873
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 groupCourse Location:
- followed by the course location.*$
- ending with zero or more charactersThen 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, ":")>
Upvotes: 3
Reputation: 1738
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>
Upvotes: 3