I am trying to work on regular expressions. I have a mainframe file which has several fields. I have a flat file parser which distinguishes several types of records based on the first three letters of every line. How do I write a regular expression where the first three letters are 'CTR'.
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
The end of the line is expressed with the dollar sign ($) in the regex. The end of the line will be put at the end of the regex pattern and the required pattern will be specified before the $ sign. The end of the line character is generally used to “line ends with a word, character, characters set, number, etc.”.
Beginning of line or beginning of string?
/^CTR.*$/
/
= delimiter^
= start of stringCTR
= literal CTR$
= end of string.*
= zero or more of any character except newline
/^CTR.*$/m
/
= delimiter^
= start of lineCTR
= literal CTR$
= end of line.*
= zero or more of any character except newlinem
= enables multi-line mode, this sets regex to treat every line as a string, so ^
and $
will match start and end of line
While in multi-line mode you can still match the start and end of the string with \A\Z
permanent anchors
/\ACTR.*\Z/m
\A
= means start of stringCTR
= literal CTR.*
= zero or more of any character except newline\Z
= end of stringm
= enables multi-line mode
As such, another way to match the start of the line would be like this:
/(\A|\r|\n|\r\n)CTR.*/
or
/(^|\r|\n|\r\n)CTR.*/
\r
= carriage return / old Mac OS newline\n
= line-feed / Unix/Mac OS X newline\r\n
= windows newline
Note, if you are going to use the backslash \
in some program string that supports escaping, like the php double quotation marks ""
then you need to escape them first
so to run \r\nCTR.*
you would use it as "\\r\\nCTR.*"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With