Fortran-regex is a Modern Fortran port of the tiny-regex-c library for regular expressions. It is based on the original C implementation, but the API is modelled in Fortran style, which is similar to the intrinsic index function.
The main API is modelled around Fortran's index intrinsic function (which performs a simple search for a substring within a string):
! Simple regex result = REGEX(string, pattern) ! Regex with output matched pattern length result = REGEX(string, pattern, length)- If the pattern command is invalid,
result = -1. - If no substrings with the given pattern are found, with a valid pattern
result = 0. This is also returned if the string has zero length, and that is an acceptable answer for the input pattern. - Otherwise, if the pattern was found
result > 0equal to the leftmost location inside the string where the pattern can be found.lengthreturns the number of consecutive characters that match this pattern
One can also parse a regex pattern into a type(regex_op) structure, and use that instead of a string pattern. I have no idea why this should be useful, but at least it's given with a consistent interface
The original tiny-regex-c code has been significantly refactored, to:
- Remove all references to
NULLcharacter string termination, and replace them with Fortran's string intrinsics (len,len_trim, etc.) - Remove all C escaped characters (
\n,\t, etc), replace with Fortran syntax. - Even in presence of strings, use
pureelementalfunctions wherever possible - It is a standalone module that has no external dependencies besides compiler modules.
! Demonstrate use of regex program test_regex use regex_module implicit none integer :: idx,ln character(*), parameter :: text = 'table football' idx = REGEX(string=text,pattern='foo*',length=ln); ! Prints "foo" print *, text(idx:idx+ln-1) end program! Demonstrate use of object-oriented interface program test_regex use regex_module implicit none integer :: idx,ln character(*), parameter :: text = 'table football' type(regex_op) :: re ! Parse pattern into a regex structure re = parse_pattern('foo*') idx = REGEX(string=text,pattern=re,length=ln); ! Prints "foo" print *, text(idx:idx+ln-1) end program- Add a
BACKoptional keyword to return the last instance instead of the first. - Option to return ALL instances as an array, instead of the first/last one only.
- Replace fixed-size static storage with allocatable character strings (slower?)
Please report any problems! It is appreciated. The original C library had hacks to account for the fact that several special characters are read in with escaped sequences, which partially collides with the escaped sequence options in regex. So, expect the current API to be still a bit rough around the edges.
fortran-regex is released under the MIT license. The code it's based upon is in the public domain.