Regular Expressions in Fortran
Fortran offers support for regular expressions through external libraries such as the PCRE (Perl Compatible Regular Expressions) library. Here are some examples of common regexp-related tasks in Fortran using PCRE.
program regular_expressions
use, intrinsic :: iso_c_binding
use pcre
implicit none
type(c_ptr) :: re
integer :: rc, n_matches
integer, parameter :: max_matches = 10
type(pcre_match) :: matches(max_matches)
character(len=100) :: subject
character(len=30) :: pattern
! This tests whether a pattern matches a string.
pattern = 'p([a-z]+)ch'
subject = 'peach'
rc = pcre_match(pattern, subject, matches, n_matches)
if (rc >= 0) then
print *, 'Match found'
else
print *, 'No match'
end if
! Compile an optimized regex pattern
re = pcre_compile(pattern, 0)
if (.not. c_associated(re)) then
print *, 'Error compiling regex'
stop
end if
! Find the match for the regexp
subject = 'peach punch'
rc = pcre_exec(re, subject, matches, n_matches)
if (rc >= 0) then
print *, 'Match found:', subject(matches(1)%start:matches(1)%end)
end if
! Find the start and end indexes for the match
print *, 'idx:', matches(1)%start, matches(1)%end
! Find submatch information
if (rc >= 2) then
print *, 'Submatch:', subject(matches(2)%start:matches(2)%end)
end if
! Find all matches
subject = 'peach punch pinch'
rc = pcre_exec(re, subject, matches, n_matches)
do while (rc >= 0)
print *, 'Match:', subject(matches(1)%start:matches(1)%end)
rc = pcre_exec(re, subject(matches(1)%end+1:), matches, n_matches)
end do
! Replace subsets of strings
call pcre_replace(re, subject, '<fruit>', subject)
print *, 'Replaced:', trim(subject)
call pcre_free(re)
end program regular_expressions
This Fortran program demonstrates various regular expression operations using the PCRE library. It includes pattern matching, compiling regular expressions, finding matches and submatches, finding all matches, and replacing substrings.
Note that Fortran doesn’t have built-in regular expression support, so we’re using an external library (PCRE) for this functionality. The exact syntax and available operations may vary depending on the specific regular expression library you choose to use with Fortran.
To use this program, you would need to have the PCRE library installed and properly linked to your Fortran compiler. The exact compilation and linking process will depend on your specific development environment.
For a complete reference on using regular expressions with Fortran, you should consult the documentation of the regular expression library you’re using (in this case, PCRE).