Home > Net >  Perl regex can't find match
Perl regex can't find match

Time:10-01

So I'm working on my own little formatting correction script that uses Perl regex for substitution, but I can't get this one to match. I've used similar matching for other fixes but this one doesn't work and I can't figure out why.

# basically takes in a string to modify and the match and substitution strings
perlRegex(){
  PERL_BADLANG=0 perl -le '
  $string = '"'"''"${1}"''"'"';
  $string =~ s/'"${2}"'/'"${3}"'/gm;
  print "$string\n";
  exit';
}

LINE_BREAK='\n'

# contents is the example below
EDITED=$(cat file.txt);
EDITED=$(perlRegex "${EDITED}" '(?<='"${LINE_BREAK}"')(  )([^{] {$'"${LINE_BREAK}"')([^\s][^;] ;$)' '$1$2$1$1$3')

My current attempt is https://regex101.com/r/vgatOd/1 which gives me the output I want.

(?<=\n)( )([^{] {$\n)([^\s][^;] ;$) to $1$2$1$1$3

(?<=\n)( ) $1: copies the spaces at the beginning of the line

([^{] {$\n) $2: captures the remaining content of the line with ending {

([^\s][^;] ;$) $3: captures the next line without a leading spaces, with ending ;

The substitution will add the spaces twice on before the second line.

Example input:


    if (debug) {
Tools.DebugLine("Log");
    }

Aim is to pad the Tools line to be at the correct column:


    if (debug) {
        Tools.DebugLine("Log");
    }

Given the regex101 does what I would like it to do, I'm perplexed as to what part of it does not work in Perl regex.

CodePudding user response:

Solved by changing to just using \n instead of $ along with them

https://regex101.com/r/poQlwm/1

(?<=\n)([ ] )([^{] \{\n)([^\s][^;] ;\n)

CodePudding user response:

Taken approach to make java file formatting isn't error prone, you should consider a better way to achieve the desired effect.

The chosen regular expression is quite excessive and mixes \n, , \s all of which falls under \s class.

The following demo code strips regular expression for simplification.

use strict;
use warnings;

my $data = do { local $/; <DATA> };
my $re = qr/([^\n] ?\{\s )(\S ?;)(\s \})/;
my $indent = ' ' x 8;

$data =~ s/$re/$1${indent}$2$3/gsm;

print $data;

__DATA__
    if (debug) {
Tools.DebugLine("Log");
    }

Output

    if (debug) {
        Tools.DebugLine("Log");
    }

Please see Perl regular expressions

  • Related