简体   繁体   中英

Regex searching and adding characters

I'm trying to use regex to add $ to the start of words in a string such that:

Answer = partOne + partTwo

becomes

$Answer = $partOne + $partTwo

I'm using / [az]/ to locate them but not sure what I'm meant to replace it with.

Is there anyway to do it with regex or am I suppose to just split up my string and put in the $?

I'm using perl right now.

You can match word boundary \\b , followed by word class \\w

my $s = 'Answer = partOne + partTwo';

$s =~ s|\b (?= \w)|\$|xg;

print $s;

output

$Answer = $partOne + $partTwo
(\w+)

You can use this.Replace by \\$$1 .

See demo.

http://regex101.com/r/lS5tT3/40

You could use a lookahead to match only the space or start of a line anchor which was immediately followed by an alphabet. Replace the matched space character or starting anchor with a $ symbol.

use strict;
use warnings;

while(my $line = <DATA>) {
    $line =~ s/(^|\s)(?=[A-Za-z])/$1\$/g;
    print $line;
}

__DATA__
Answer = partOne + partTwo

Output:

$Answer = $partOne + $partTwo

Perl's regexes have a word character class \\w that is meant for exactly this sort of thing. It matches upper-case and lower-case letters, decimal digits, and the underscore _ .

So if you prefix all ocurrences of one or more such characters with a dollar then it will achieve what you ask. It would look like this

use strict;
use warnings;

my $str = 'Answer = partOne + partTwo';

$str =~ s/(\w+)/\$$1/g;

print $str, "\n";

output

$Answer = $partOne + $partTwo

But please note that, if the text you're processing is a programming language, this will also process all comments and string literals in a way you probably don't want.

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