简体   繁体   中英

Regex - Find string in line but replace another string in the same line

I have problem with find and replace in Perl regex syntax:

I have the following lines:

FILEGROUP [PAYMENT_MGMT](NAME = [PAYMENT_MGMT], FILENAME = '$(DefaultDataPath)$(DatabaseName)_PAYMENT_MGMT.ndf', FILEGROWTH = 102400 KB)

LOG ON (NAME = [SQL_log], FILENAME = '$(DefaultLogPath)$(DatabaseName)_log.ldf', SIZE = 5012 KB, MAXSIZE = 2097152 MB, FILEGROWTH = 102400 MB) COLLATE Slovenian_CI_AS

SO i have to find string SQL_log but replace only SIZE = with SIZE = 1024

How can i achieve this with regex PCRE ?

Once again all the solutions are cramming everything into a single regex. I don't understand why people do this; it doesn't happen with any other part of the language

This is much more clearly written as

if ( /NAME \s* = \s* \[SQL_log\]/x ) {

    s/SIZE \s* = \s* \K \d+/1024/x;

}

I found the answer!

Search:

(IGP_log.*?\bSIZE\b\s=)(\s[0-9]+) 

Replace:

\1 1024

or

${1} 1024

If you are guaranteed that you won't ever have more than one SQL_log record on the same line, or that SQL_log LOG records always have "NAME =" AND "SIZE =" in that order, the following ought to be a safe solution:

s/\b(NAME\s*=\s*\[SQL_log\].+?\bSIZE\s*=\s*)[^,)]*/${1}1024 KB/

If you can't guarantee that "NAME =" and "SIZE =" will ALWAYS be in that order but you CAN guarantee there will never be more than one per line, you will need this in addition:

s/\b(SIZE\s*=\s*)[^,]*(.+?\bNAME\s*=\s*\[SQL_log\])/${1}1024 KB$2/

Capture everything before the target and put it back in the replace:

$x =~ s/^(.*?SQL_log.*?SIZE = )\d+/${1}1024/;

Test code:

$x = "foo SQL_log bar SIZE = 5012 baz";
$x =~ s/^(.*?SQL_log.*?SIZE = )\d+/${1}1024/;
print $x;

Output:

foo SQL_log bar SIZE = 1024 baz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM