Reading .txt File into String and Matching with RegEx

BoQsc vaidas.boqsc at gmail.com
Mon Dec 11 14:12:09 UTC 2023


Matches function declarations and captures function names from 
`.d` Source Code file


**regexcapture.d**

```
import std.stdio : writeln;
import std.regex : matchAll, regex;
import std.file  : read;

void main(){
	string input = cast(string)read("sourcecode.d");

	foreach(match; matchAll(input, 
regex(r"\b([A-Za-z_]\w*)\s*\([^)]*\)\s*", "g"))){
		writeln(match.captures()[1]);
	}
}
```

**Input(sourcecode.d)**
```
     BOOL WaitNamedPipeA(LPCSTR, DWORD);
     BOOL WaitNamedPipeW(LPCWSTR, DWORD);
     BOOL WinLoadTrustProvider(GUID*);
     BOOL WriteFile(HANDLE, PCVOID, DWORD, PDWORD, LPOVERLAPPED);
     BOOL WriteFileEx(HANDLE, PCVOID, DWORD, LPOVERLAPPED, 
LPOVERLAPPED_COMPLETION_ROUTINE);
     BOOL WritePrivateProfileSectionA(LPCSTR, LPCSTR, LPCSTR);
     BOOL WritePrivateProfileSectionW(LPCWSTR, LPCWSTR, LPCWSTR);
     BOOL WritePrivateProfileStringA(LPCSTR, LPCSTR, LPCSTR, 
LPCSTR);
     BOOL WritePrivateProfileStringW(LPCWSTR, LPCWSTR, LPCWSTR, 
LPCWSTR);
```
Note: This small input excerpt was taken from a real source code 
file: 
https://github.com/dlang/dmd/blob/master/druntime/src/core/sys/windows/winbase.d#L2069-L2078

**Output**
```

C:\Users\Windows10\Documents\matchtest>rdmd regexcapture.d
WaitNamedPipeA
WaitNamedPipeW
WinLoadTrustProvider
WriteFile
WriteFileEx
WritePrivateProfileSectionA
WritePrivateProfileSectionW
WritePrivateProfileStringA
WritePrivateProfileStringW
```

---
Relevant links:
https://dlang.org/phobos/std_regex.html#regex
https://dlang.org/phobos/std_regex.html#.RegexMatch.captures
https://regexr.com/


More information about the Digitalmars-d-learn mailing list