How can I combine at the beginning of any line, including the first, with a Perl regex?

According to the Perl documentation for regular expressions :

By default, the character "^" is guaranteed to correspond only to the beginning of a line ... Inline lines of a new line will not be matched by a symbol "^" ... However, you can treat the line as a multi-line buffer, so that "^" will match after any new line inside the line ... you can do this using the / m modifier for the pattern matching operator.

The “after any new line” part means that it will only match at the beginning of the second and subsequent lines. What if I want to combine at the beginning of the line any (1st, 2nd, etc.)?

EDIT: OK, it seems that at first the file has specification information (3 characters) and that they confuse me. Any way to get ^ anyway?

EDIT: So, in the end it works (there is no specification yet), but now it seems that the Perl documentation is wrong, as it says “after any new line”

+4
source share
4 answers

You can use the regular expression /^(?:\xEF\xBB\xBF)?/mg so that it matches at the beginning of the line if you want to keep the specification.

+3
source

^ matches the 1st line with the /m flag:

 ~:1932$ perl -e '$a="12\n23\n34";$a=~s/^/:/gm;print $a' :12 :23 :34 

To meet the specification, you need to include it in compliance.

 ~:1939$ perl -e '$a="12\n23\n34";$a=~s/^(\d)/<\1>:/mg;print $a' 12 <2>:3 <3>:4 ~:1940$ perl -e '$a="12\n23\n34";$a=~s/^(?:)?(\d)/<\1>:/mg;print $a' <1>:2 <2>:3 <3>:4 
+3
source

It is conceptually assumed that a new line is assumed before the start of a line. Therefore, / ^ a / will find the letter 'a' at the beginning of the line.

+1
source

Put an empty line at the beginning of the file, these are cool things down and avoid reading regex hard.

Yes, specification. It may appear at the beginning of the file, so put an empty one at the beginning of the file. The specification will not be \s , or something can be seen with the eye. It kills my watch when the spec makes my regex fail.

-1
source

Source: https://habr.com/ru/post/1303970/


All Articles