Regular expression to match characters at beginning of line only [closed]
Solution 1:
Beginning of line or beginning of string?
Start and end of string
/^CTR.*$/
/
= delimiter^
= start of stringCTR
= literal CTR$
= end of string.*
= zero or more of any character except newline
Start and end of line
/^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.*"
Solution 2:
^CTR
or
^CTR.*
edit:
To be more clear: ^CTR
will match start of line and those chars. If all you want to do is match for a line itself (and already have the line to use), then that is all you really need. But if this is the case, you may be better off using a prefab substr()
type function. I don't know, what language are you are using. But if you are trying to match and grab the line, you will need something like .*
or .*$
or whatever, depending on what language/regex function you are using.
Solution 3:
Regex symbol to match at beginning of a line:
^
Add the string you're searching for (CTR
) to the regex like this:
^CTR
Example: regex
That should be enough!
However, if you need to get the text from the whole line in your language of choice, add a "match anything" pattern .*
:
^CTR.*
Example: more regex
If you want to get crazy, use the end of line matcher
$
Add that to the growing regex pattern:
^CTR.*$
Example: lets get crazy
Note: Depending on how and where you're using regex, you might have to use a multi-line modifier to get it to match multiple lines. There could be a whole discussion on the best strategy for picking lines out of a file to process them, and some of the strategies would require this:
Multi-line flag m
(this is specified in various ways in various languages/contexts)
/^CTR.*/gm
Example: we had to use m on regex101
Solution 4:
Try ^CTR.\*
, which literally means start of line, CTR, anything.
This will be case-sensitive, and setting non-case-sensitivity will depend on your programming language, or use ^[Cc][Tt][Rr].\*
if cross-environment case-insensitivity matters.