正则表达式只匹配行首的字符 [英] Regular expression to match characters at beginning of line only
问题描述
我正在尝试处理正则表达式.我有一个包含多个字段的大型机文件.我有一个平面文件解析器,它根据每行的前三个字母区分几种类型的记录.如何编写前三个字母为CTR"的正则表达式.
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'.
推荐答案
行的开头还是字符串的开头?
Beginning of line or beginning of string?
/^CTR.*$/
/
= 分隔符^
= 字符串开始CTR
= 文字点击率$
= 字符串结束.*
= 除换行符外的零个或多个任何字符
/
= delimiter
^
= start of string
CTR
= literal CTR
$
= end of string
.*
= zero or more of any character except newline
/^CTR.*$/m
/
= 分隔符^
= 行首CTR
= 文字点击率$
= 行尾.*
= 除换行符之外的零个或多个任何字符m
= 启用多行模式,这将正则表达式设置为将每一行视为一个字符串,因此 ^
和 $
将匹配开始和结束线
/
= delimiter
^
= start of line
CTR
= literal CTR
$
= end of line
.*
= zero or more of any character except newline
m
= enables multi-line mode, this sets regex to treat every line as a string, so ^
and $
will match start and end of line
在多行模式下,您仍然可以使用 \A\Z
永久锚点来匹配字符串的开头和结尾
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
= 表示字符串的开始CTR
= 文字点击率.*
= 除换行符之外的零个或多个任何字符\Z
= 字符串结束m
= 启用多行模式
\A
= means start of string
CTR
= literal CTR
.*
= zero or more of any character except newline
\Z
= end of string
m
= 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.*/
或
/(^|\r|\n|\r\n)CTR.*/
\r
= 回车/旧的 Mac OS 换行符\n
= 换行符/Unix/Mac OS X 换行符\r\n
= windows 换行符
\r
= carriage return / old Mac OS newline
\n
= line-feed / Unix/Mac OS X newline
\r\n
= windows newline
注意,如果你打算在一些支持转义的程序字符串中使用反斜杠 \
,比如 php 双引号 ""
那么你需要对它们进行转义先
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
所以要运行 \r\nCTR.*
你会使用它作为 "\\r\\nCTR.*"
so to run \r\nCTR.*
you would use it as "\\r\\nCTR.*"
这篇关于正则表达式只匹配行首的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!