aboutsummaryrefslogtreecommitdiff
path: root/src/functionregex.cpp
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/functionregex.cpp126
1 files changed, 126 insertions, 0 deletions
diff --git a/src/functionregex.cpp b/src/functionregex.cpp
new file mode 100644
index 0000000..f0abc35
--- /dev/null
+++ b/src/functionregex.cpp
@@ -0,0 +1,126 @@
1#include "functionregex.h"
2
3#include <bu/regex.h>
4#include <bu/plugger.h>
5PluginInterface3( pluginFunctionRegEx, regex, FunctionRegEx, Function,
6 "Mike Buland", 0, 1 );
7
8FunctionRegEx::FunctionRegEx()
9{
10}
11
12FunctionRegEx::~FunctionRegEx()
13{
14}
15
16Bu::FString FunctionRegEx::getName() const
17{
18 return "regex";
19}
20
21Variable FunctionRegEx::call( Variable &input, VarList lParams )
22{
23 if( lParams.getSize() == 1 )
24 {
25 Bu::RegEx re( lParams.first().getString() );
26 switch( input.getType() )
27 {
28 case Variable::typeString:
29 return re.execute( input.getString() );
30
31 case Variable::typeList:
32 {
33 Variable vOut( Variable::typeList );
34 for( VarList::iterator i = input.begin(); i; i++ )
35 {
36 if( re.execute( (*i).toString() ) )
37 vOut.append( *i );
38 }
39 return vOut;
40 }
41 break;
42
43 default:
44 break;
45 }
46 }
47 else if( lParams.getSize() == 2 )
48 {
49 Bu::RegEx re( lParams.first().getString() );
50 Bu::FString sPat = lParams.last().getString();
51 switch( input.getType() )
52 {
53 case Variable::typeString:
54 if( re.execute( input.getString() ) )
55 {
56 return replace( re, input.getString(), sPat );
57 }
58 else
59 {
60 return input;
61 }
62 break;
63
64 case Variable::typeList:
65 {
66 Variable vOut( Variable::typeList );
67 for( VarList::iterator i = input.begin(); i; i++ )
68 {
69 if( re.execute( (*i).toString() ) )
70 vOut.append( replace( re, (*i).toString(), sPat ) );
71 else
72 vOut.append( *i );
73 }
74 return vOut;
75 }
76 break;
77
78 default:
79 break;
80 }
81 }
82 throw Bu::ExceptionBase(
83 "regex does not work on non-string or non-list types.");
84}
85
86Bu::FString FunctionRegEx::replace( Bu::RegEx &re, const Bu::FString &sSrc,
87 const Bu::FString &sPat )
88{
89 Bu::FString sOut;
90
91 int iStart, iEnd;
92 re.getSubStringRange( 0, iStart, iEnd ); // Get the range of the full match
93
94 if( iStart > 0 )
95 sOut.append( sSrc, 0, iStart );
96
97 for( Bu::FString::const_iterator i = sPat.begin(); i; i++ )
98 {
99 if( *i == '\\' )
100 {
101 i++;
102 if( *i <= '9' && *i >= '0' )
103 {
104 int iInd = *i-'0';
105 if( iInd < re.getNumSubStrings() )
106 sOut += re.getSubString( iInd );
107 }
108 else
109 {
110 sOut += *i;
111 }
112 }
113 else
114 {
115 sOut += *i;
116 }
117 }
118
119 if( iEnd < sSrc.getSize() )
120 {
121 sOut.append( sSrc, iEnd, -1 );
122 }
123
124 return sOut;
125}
126