Skip to content

Commit

Permalink
feat: split function
Browse files Browse the repository at this point in the history
  • Loading branch information
Demali-876 committed Jan 12, 2025
1 parent c8baf33 commit 3a16404
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/Matcher.mo
Original file line number Diff line number Diff line change
Expand Up @@ -340,5 +340,52 @@ module {
}
}
};
public func split(nfa : NFA, text : Text, maxSplit : ?Nat, flags : ?Flags) : Result.Result<[Text], MatchError> {
let splitLimit = switch (maxSplit) {
case (null) 0;
case (?val) val
};

if (text.size() == 0) {
return #err(#EmptyExpression("Empty expression"))
};

switch (findAll(nfa, text, flags)) {
case (#err(e)) #err(e);
case (#ok(delimiterMatches)) {
let results = Buffer.Buffer<Text>(delimiterMatches.size());
var lastIndex = 0;
var splitCount = 0;

label splitting for (delimMatch in delimiterMatches.vals()) {
if (splitLimit > 0 and splitCount >= splitLimit) {
break splitting
};
if (delimMatch.position.0 == delimMatch.position.1 and delimMatch.position.0 == 0) {
continue splitting
};
if (lastIndex < delimMatch.position.0) {
results.add(substring(text, lastIndex, delimMatch.position.0))
};
switch (delimMatch.capturedGroups) {
case (?groups) {
if (groups.size() > 0) {
results.add(delimMatch.value)
}
};
case (null) {}
};

lastIndex := delimMatch.position.1;
splitCount += 1
};
if (lastIndex < text.size()) {
results.add(substring(text, lastIndex, text.size()))
};

#ok(Buffer.toArray(results))
}
}
};
}
}
8 changes: 8 additions & 0 deletions src/lib.mo
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ module {
};
}
};
public func split(text: Text, maxSpilt:?Nat) : Result.Result<[Text], RegexError> {
switch (nfa) {
case (null) #err(#NotCompiled);
case (?compiledNFA) {
matcher.split(compiledNFA, text, maxSpilt, flags)
};
}
};
public func enableDebug(b:Bool){
matcher.debugMode(b);
}
Expand Down

0 comments on commit 3a16404

Please sign in to comment.