i m trying to make rename program with delphi and need to know if it s possible to match some specified number of characters from the beginning, using regex.
for example if the string is FileName.txt and the specific number is 6
it should match FileNa
i also need a pattern to match string from a specific number to the end.
i would be glad if answers include descriptions because i would like to learn regex coding.
If you use Delphi XE, regular expression functionality is build in with the
TRegExclass. If you use an earlier version of Delphi you can find a library here, where you can also find more about the Delphi XE support: http://www.regular-expressions.info/delphi.htmlThis regular expression matches up to 6 characters until the
.separating the extension from the rest of the file name.Given the input: FileName.txt
Group 1 would be: FileNa
Given the input: File.txt
Group 1 would be: File
The expression uses grouping to capture the first 6 characters. The code in Delphi XE would look something like:
For instance the filename: FileName.txt will be matched with: FileNa (group 1)
I’ll try to explain the regular expression I have used, although there are probably better expressions out there:
To the next part of your question, creating a pattern to match a string from a specific number to the end:
Given the input: This is a test
Group 1 would be: s a test
In this example the specific number is 6, change it to whatever number you are looking for. Again I’ve used groups to get the contents of the matched text. The first group is a none capturing group, meaning we are not interested in its content, only that we need it to be there. If we are still talking about filenames you can use the following regular expression:
Given the input: FileName.txt
Group 1 would be: me
This is a modification of the first regular expression, where I’ve made the first group none capturing, told it to be 6 characters long (again change to whatever number suits you). And excluded the extension from the captured text.
Remember that regular expressions are easier to compose than to read. I always found that: http://www.regular-expressions.info/ is a good source of information, besides this book has helped me a great deal: Mastering Regular Expressions.