I want to search a sentence and replace it with the value of hash that matched string like this:
my $sentence = "abc def hello hi";
$sentence =~ s/abc def/$hash{'abc def'}/g;
I am not getting the correct output.
Can any one please help me?
This works for me:
#!/usr/bin/env perl
use strict;
use warnings;
my %hash = ( 'abc def' => 'pqr xyz' );
my $sentence = "abc def hello hi";
$sentence =~ s/abc def/$hash{'abc def'}/g;
print "$sentence\n";
When run, it prints:
pqr xyz hello hi
If that's not what you expected, what were you expecting? (Note that there were a number of typos in the original version of the Perl code in the question; I assumed they were incidental, but maybe they were key to your problem. Using use strict; and use warnings; helps spot problems such as misspelled variable names.)
Related
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.
I want to extract the number only.
use strict;
use warnings;
my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;
print $line; #prints *ABMA 1234*
Is my regular expression incorrect?
If you want to print 1234, you need to change your regex and print the 2nd match:
use strict;
use warnings;
my $line = "ABMA 1234";
$line =~ /(\s)(\d{4})/;
print $2;
You can replace the exact value with the corresponding values. And your are not removing the text \w;
use strict;
use warnings;
my $line = "ABMA 1234";
$line=~s/([A-z]*)\s+(\d+)/$2/;
print $line; #prints only 1234
If you want to store the value in the new string then
(my $newstring = $line)=~s/([A-z]*)\s+(\d+)/$2/;
print $newstring; #prints only 1234
Just try this:
I don't know how you output the match in perl but you can use below regex for output the full match in your regex, you might getting space appended with your result in your current regex.
\b[\d]{4}
DEMO
I am reading another perl file line by line and need to find any words or set of words surround by single or double quotations. This is an example of the code I am reading in:
#!/usr/bin/env perl
use strict;
use warnings;
my $string = 'Hello World!';
print "$string\n";
Basically, I need to find and print out 'Hello World!' and "$string\n".
I've read my file in fine and stored its contents in an array. From there I'm looping over each line and find the desired set of words in the quotations using regex as such:
for(#contents) {
if(/\"|\'[^\"|\']*\"|\'/) {
print $_."\n";
}
}
which gives me the following output:
my $string = 'Hello World!';
print "$string\n";
I tried splitting the contents by whitespace and then trying to find a match, but that gives me this:
'Hello
World!'
"$string\n";
I've tried numerous solutions other suggested on here but to no avail. I have also tried Text::ParseText and using parse_line, but that gives me the complete wrong output.
Any ideas that could help me?
Just need to add some capturing parenthesis to your regex, instead of printing the whole line
use strict;
use warnings;
while (<DATA>) {
if(/(["'][^"']*["'])/) {
print "$1\n";
}
}
__DATA__
#!/usr/bin/env perl
use strict;
use warnings;
my $string = 'Hello World!';
print "$string\n";
Note, there are plenty of flaws in your regex though. For example '\'' Won't match properly. Neither will "He said 'boo'". To get closer you'll have to do some balanced parenthesis checking, but there isn't going to be any perfect solution.
For a solution that is a little closer, you could use the following:
if(/('(?:(?>[^'\\]+)|\\.)*'|"(?:(?>[^"\\]+)|\\.)*")/) {
That would take care of my above exceptions and also strings like print "how about ' this \" and ' more \n";, but there are still edge cases like the use of qq{} or q{}. Not to mention strings that span more than one line.
In other words, if your goal is perfect, this project may be outside of the scope of most people's skills, but hopefully the above will be of some help.
Maybe you can have more than one "string" to capture per line, one solution could be:
while(my $line=<STDIN>) {
while( $line =~ /[\'\"](.*?)[\'\"]/g ) {
print "matched: '$1'\n";
}
}
ie, input:
#!/usr/bin/env perl
use strict;
use warnings;
my $string = 'Hello World!' . 'asdsad';
print "$string\n";
and executing the code will give you:
matched: 'Hello World!'
matched: 'asdsad'
matched: '$string\n'
My string looks like this
important stuff: some text 2: some text 3.
I want to only print "important stuff". So basically I want to print everything up to the first colon. I'm sure this is simple, but my regex foo is not so good.
Edit: Sorry I was doing something stupid and gave you a bad example line. It has been corrected.
Just restrict what you're matching to non-colons, [^:]*. Note, the ^ and : boundaries aren't actually needed, but they help document the intent behind the regex.
my $text = "important stuff: some text 2: some text 3."
if ($text =~ /^([^:]*):/) {
print "$1";
}
Consider just splitting on the colon:
use strict;
use warnings;
my $string = 'important stuff: some text 2: some text 3.';
my $important = ( split /:/, $string )[0];
print $important;
Output:
important stuff
Well, assume its a string
$test = "sass sg22gssg 22222 2222: important important :"
Assume you want all characters between.
Wrong answer: $test =~ /:(.+):/; # thank you for the change from .{1,}
Corrected.
$test =~ /:([^:]*):/;
print $1; #perl memory u can assign to a string ;
$found = $1;
As a cheat sheet of regex in perl. cheat sheet
I did test it.
I have an odd situation where I want to remove all but the first match of a substring inside of a very long undelimited string. I have found some similar topics here, but none quite like mine.
For simplicities sake, here are some sudo before and after strings.
I have an undelimited file where "c" could be thousands of random characters but "bbb" is a unique string:
aaabbbbbbccccccbbbccccccbbbccccccaaa
I want to remove all but the first bbb:
aaabbbccccccccccccccccccaaa
Also, I would like to be able to use this as a perl script I can pipe through:
cat file.in | something | perl -pe 's/bbb//g' | somethingelse > file.out
But, unlike my example above, I want to leave the first occurrence of "bbb" intact."
This seems like it should be fairly easy, but it is stumping me.
Any ideas?
Thanks in advance!
Perhaps the following will be helpful:
use strict;
use warnings;
my $string = 'aaabbbbbbccccccbbbccccccbbbccccccaaa';
$string =~ s/(?<=bbb).*?\Kbbb//g;
print $string;
Output:
aaabbbccccccccccccccccccaaa
my $string = 'aaabbbbbbccccccbbbccccccbbbccccccaaa';
my $seen;
sub first {
$seen++;
return $_[0] if $seen eq 1;
return '';
}
$string =~ s/(bbb)/first($1)/ge;
say $string;
Outputs:
aaabbbccccccccccccccccccaaa
I'm still pretty new to perl and regex and need some help getting started. I would love to provide some code, but that's kinda where I'm stuck.
What I'm trying to do is that I have this string in a file like this:
dn: CN=doe\, john,OU=Users,DC=domain,DC=com
and a string like this:
uid: d12345
I need to do a search and replace to get the following result.
dn: uid= d12345,OU=Users,DC=domain,DC=com
Can anyone help me get started with this one? Much thanks!
So you want to replace CN=doe\, john with uid= d12345? Try this:
$uidString = "uid: d12345";
$dnString = "dn: uid= d12345,OU=Users,DC=domain,DC=com";
if( $uidString =~ /uid: (\w+)/ ) {
$uid = $1;
$dnString =~ s/CN=.+?[^\\],/uid= $uid,/;
}
That will replace everything from CN= to the first unescaped comma with the uid.
Won't a one line regex do the trick?
use strict;
use warnings;
my $a = "dn: CN=doe\, john,OU=Users,DC=domain,DC=com";
my $b= "uid: d12345";
#the regex
$a =~ s/CN(.*?), .*?,/$b,/;
print "$a";
I suspect your DNs and uids will be dynamic. Here is something that will help. The regex will substitute CN= all the way until the comma with whatever string you put in $uid.
#!/usr/bin/env perl
use strict;
use warnings;
my $string = 'dn: CN=doe\, john,OU=Users,DC=domain,DC=com';
my $uid_str = 'uid: d12345';
my ($uid) = $uid_str =~ m/^uid:(.+)$/;
$string =~ s/CN=.+(,OU=.+$)/uid=$uid$1/;
print "String is: $string\n";
Output: String is: dn: uid= d12345,OU=Users,DC=domain,DC=com