Sponsored Content
Top Forums Shell Programming and Scripting Perl, RegEx - Help me to understand the regex! Post 302946690 by alex_5161 on Thursday 11th of June 2015 11:36:59 AM
Old 06-11-2015
Perl, RegEx - Help me to understand the regex!

I am not a big expert in regex and have just little understanding of that language.
Could you help me to understand the regular Perl expression:
Code:
^(?!if\b|else\b|while\b|[\s\*])(?:[\w\*~_& ;]+?\s+){1,6}([\w:\*~_&]+\s*)\([^\);]*\)[^\{;] *?(?:^[^\r\n\{]*;?[\s]+){0,10}\{

------
This is regex to select functions from a C/C++ source and defined in UltraEdit (if interested where it is from)
It works.
I able to use it in my perl script by applying 'm' - multyline regex and having whole file as one string (by 'undef $/')
------
I am going to show here my understanding how much I have and will ask where I do not know what is happening.
------
Please, correct me, if I am wrong in any assumption and give me an idea where I do not have any!
Thanks!
================
So, as I understanding this regex so far, is:
Code:
#initial:
"^(?!if\b|else\b|while\b|[\s\*])(?:[\w\*~_&]+?\s+){1,6}([\w:\*~_&]+\s*)\([^\);]*\)[^\{;]*?(?:^[^\r\n\{]*;?[\s]+){0,10}\{"

#by pieces:
# 1.
"^(?!if\b|else\b|while\b|[\s\*]) # - on beginning DOES NOT have words: 'if','esle','while' or (' ' and '*')
                                 # I guess, '(?!' part means do not select this part (defined by stuff in '(...)')
# 2.
(?:[\w\*~_&]+?\s+){1,6}          # - allowed beginning: any alpha-numeric or '*','~','_' and '&' one or more (shortest) (by +?),
                                 #   followed by ' 's (1 or more) (so, should be a word) , repeating from 1 to 6 times
                                 # Again: '(?:' - do not save it in final selection
# 3.
([\w:\*~_&]+\s*)\([^\);]*\)      # world-chars(plus '*~_&) one+ times; space{0,} (saved as $1), followed by '(...)' without ';' inside
# 4.
[^\{;]*?                         # - no ';' and '{' - any time repeated, but shortest (by *?)
                                 # so, IS IT anything between <func_nm>(..)  and   {...}  ?  So, comments only?
# 5.
(?:^[^\r\n\{]*;?[\s]+){0,10}     # ????  - This I do not understand:
                                 # what is '^[^' ? - beginning and NOT-block?  How it could be beginning? Is it in multyline selection means
                                 # anything on new line?
                                 # After that the \r\n - so, line change.  After 'on beginning' no line change?! So, one new line is fine, but
                                 # two is not???  Seems, nonsense.  How to understand?
                                 #  - Followed by ';' ?!?!  Statement between <fnc_nm>(...) and {...} ?!?!?  - Nonsense?!?!
                                 # after that '?' -so, shortest?
                                 # - folowed by spaces, at least one; and it could be up to 10 times (but do not save it (by (?: on beginning)
                                 # This understanding seems to me unreasonable.
                                 # Help me to get it!
# 6.
\{"                              # Finaly, followed by '{'

Thanks!

Last edited by alex_5161; 06-12-2015 at 01:38 PM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

q with Perl Regex

For a programming exercise, I am mean to design a Perl script that detects double letters in a text file. I tried the following expressions # Check for any double letter within the alphabet /+/ # Check for any repetition of an alphanumeric character /\w+/ Im aware that the... (8 Replies)
Discussion started by: JamesGoh
8 Replies

2. Shell Programming and Scripting

Perl REGEX

Hi, Can anyone help me to find regular expression for the following in Perl? "The string can only contain lower case letters (a-z) and no more than one of any letter." For example: "table" is accepted, whether "dude" is not. I have coded like this: $str = "table"; if ($str =~ m/\b()\b/) {... (4 Replies)
Discussion started by: evilfreakz
4 Replies

3. Shell Programming and Scripting

Can't quite understand this regex

The following regular expression is found in a book I have been reading. It apparently can be used on an /etc/passwd file to find any accounts which have no password. I am having a heck of a time seeing how it works, and I was wondering if someone could run me through it. I will take a stab at... (1 Reply)
Discussion started by: kermit
1 Replies

4. Shell Programming and Scripting

Converting perl regex to sed regex

I am having trouble parsing rpm filenames in a shell script.. I found a snippet of perl code that will perform the task but I really don't have time to rewrite the entire script in perl. I cannot for the life of me convert this code into something sed-friendly: if ($rpm =~ /(*)-(*)-(*)\.(.*)/)... (1 Reply)
Discussion started by: suntzu
1 Replies

5. UNIX for Dummies Questions & Answers

Perl Regex Help!!!

Hi, I get the following when I cat a file *.log xxxxx ===== dasdas gwdgsg fdsagfsag agsdfag ===== random data ===== My output should look like : If the random data after the 2nd ==== is null then OK should be printed else the random data should be printed. How do I go about this... (5 Replies)
Discussion started by: manutd
5 Replies

6. Programming

Perl regex

HI, I'm new to perl and need simple regex for reading a file using my perl script. The text file reads as - filename=/pot/uio/current/myremificates.txt certificates=/pot/uio/current/userdir/conf/user/gamma/settings/security/... (3 Replies)
Discussion started by: jhamaks
3 Replies

7. Programming

Perl regex

Hi Guys I have the following regex $OSRELEASE = $1 if ($output =~ /(Mac OS X (Server )?10.\d)/); output is currently Mac OS X 10.7.5 when the introduction of Mac 10.8 output changes to OS X 10.8.2 they have dropped the Mac bit so i changed the regex to be (2 Replies)
Discussion started by: ab52
2 Replies

8. Shell Programming and Scripting

?= in perl regex

Could anyone please make me understand how the ?= works below .. After executing this I am getting the same output. $string="I love chocolate."; $string =~ s/chocolate(?= ice)/vanilla/; print "$string\n"; (2 Replies)
Discussion started by: scriptscript
2 Replies

9. Shell Programming and Scripting

Sendmail K command regex: adding exclusion/negative lookahead to regex -a@MATCH

I'm trying to get some exclusions into our sendmail regular expression for the K command. The following configuration & regex works: LOCAL_CONFIG # Kcheckaddress regex -a@MATCH +<@+?\.++?\.(us|info|to|br|bid|cn|ru) LOCAL_RULESETS SLocal_check_mail # check address against various regex... (0 Replies)
Discussion started by: RobbieTheK
0 Replies

10. Shell Programming and Scripting

Perl REGEX help

Experts - I found a script on one of the servers that I work on and I need help understanding one of the lines. I know what the script does, but I'm having a hard time understanding the grouping. Can someone help me with this? Here's the script... #!/usr/bin/perl use strict; use... (2 Replies)
Discussion started by: timj123
2 Replies
PERLREQUICK(1)						 Perl Programmers Reference Guide					    PERLREQUICK(1)

NAME
perlrequick - Perl regular expressions quick start DESCRIPTION
This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl. The Guide Simple word matching The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that contains that word: "Hello World" =~ /World/; # matches In this statement, "World" is a regex and the "//" enclosing "/World/" tells perl to search a string for a match. The operator "=~" associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, "World" matches the second word in "Hello World", so the expression is true. This idea has several variations. Expressions like this are useful in conditionals: print "It matches " if "Hello World" =~ /World/; The sense of the match can be reversed by using "!~" operator: print "It doesn't match " if "Hello World" !~ /World/; The literal string in the regex can be replaced by a variable: $greeting = "World"; print "It matches " if "Hello World" =~ /$greeting/; If you're matching against $_, the "$_ =~" part can be omitted: $_ = "Hello World"; print "It matches " if /World/; Finally, the "//" default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front: "Hello World" =~ m!World!; # matches, delimited by '!' "Hello World" =~ m{World}; # matches, note the matching '{}' "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin', # '/' becomes an ordinary char Regexes must match a part of the string exactly in order for the statement to be true: "Hello World" =~ /world/; # doesn't match, case sensitive "Hello World" =~ /o W/; # matches, ' ' is an ordinary char "Hello World" =~ /World /; # doesn't match, no ' ' at end perl will always match at the earliest possible point in the string: "Hello World" =~ /o/; # matches 'o' in 'Hello' "That hat is red" =~ /hat/; # matches 'hat' in 'That' Not all characters can be used 'as is' in a match. Some characters, called metacharacters, are reserved for use in regex notation. The metacharacters are {}[]()^$.|*+? A metacharacter can be matched by putting a backslash before it: "2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter "2+2=4" =~ /2+2/; # matches, + is treated like an ordinary + 'C:WIN32' =~ /C:\WIN/; # matches "/usr/bin/perl" =~ //usr/bin/perl/; # matches In the last regex, the forward slash '/' is also backslashed, because it is used to delimit the regex. Non-printable ASCII characters are represented by escape sequences. Common examples are " " for a tab, " " for a newline, and " " for a carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., "33", or hexadecimal escape sequences, e.g., "x1B": "1000 2000" =~ m(0 2) # matches "cat" =~ /143x61x74/ # matches in ASCII, but a weird way to spell cat Regexes are treated mostly as double quoted strings, so variable substitution works: $foo = 'house'; 'cathouse' =~ /cat$foo/; # matches 'housecat' =~ /${foo}cat/; # matches With all of the regexes above, if the regex matched anywhere in the string, it was considered a match. To specify where it should match, we would use the anchor metacharacters "^" and "$". The anchor "^" means match at the beginning of the string and the anchor "$" means match at the end of the string, or before a newline at the end of the string. Some examples: "housekeeper" =~ /keeper/; # matches "housekeeper" =~ /^keeper/; # doesn't match "housekeeper" =~ /keeper$/; # matches "housekeeper " =~ /keeper$/; # matches "housekeeper" =~ /^housekeeper$/; # matches Using character classes A character class allows a set of possible characters, rather than just a single character, to match at a particular point in a regex. Character classes are denoted by brackets "[...]", with the set of characters to be possibly matched inside. Here are some examples: /cat/; # matches 'cat' /[bcr]at/; # matches 'bat', 'cat', or 'rat' "abc" =~ /[cab]/; # matches 'a' In the last statement, even though 'c' is the first character in the class, the earliest point at which the regex can match is 'a'. /[yY][eE][sS]/; # match 'yes' in a case-insensitive way # 'yes', 'Yes', 'YES', etc. /yes/i; # also match 'yes' in a case-insensitive way The last example shows a match with an 'i' modifier, which makes the match case-insensitive. Character classes also have ordinary and special characters, but the sets of ordinary and special characters inside a character class are different than those outside a character class. The special characters for a character class are "-]^$" and are matched using an escape: /[]c]def/; # matches ']def' or 'cdef' $x = 'bcr'; /[$x]at/; # matches 'bat, 'cat', or 'rat' /[$x]at/; # matches '$at' or 'xat' /[\$x]at/; # matches 'at', 'bat, 'cat', or 'rat' The special character '-' acts as a range operator within character classes, so that the unwieldy "[0123456789]" and "[abc...xyz]" become the svelte "[0-9]" and "[a-z]": /item[0-9]/; # matches 'item0' or ... or 'item9' /[0-9a-fA-F]/; # matches a hexadecimal digit If '-' is the first or last character in a character class, it is treated as an ordinary character. The special character "^" in the first position of a character class denotes a negated character class, which matches any character but those in the brackets. Both "[...]" and "[^...]" must match a character, or the match fails. Then /[^a]at/; # doesn't match 'aat' or 'at', but matches # all other 'bat', 'cat, '0at', '%at', etc. /[^0-9]/; # matches a non-numeric character /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary Perl has several abbreviations for common character classes: o d is a digit and represents [0-9] o s is a whitespace character and represents [ f] o w is a word character (alphanumeric or _) and represents [0-9a-zA-Z_] o D is a negated d; it represents any character but a digit [^0-9] o S is a negated s; it represents any non-whitespace character [^s] o W is a negated w; it represents any non-word character [^w] o The period '.' matches any character but " " The "dswDSW" abbreviations can be used both inside and outside of character classes. Here are some in use: /dd:dd:dd/; # matches a hh:mm:ss time format /[ds]/; # matches any digit or whitespace character /wWw/; # matches a word char, followed by a # non-word char, followed by a word char /..rt/; # matches any two chars, followed by 'rt' /end./; # matches 'end.' /end[.]/; # same thing, matches 'end.' The word anchor "" matches a boundary between a word character and a non-word character "wW" or "Ww": $x = "Housecat catenates house and cat"; $x =~ /cat/; # matches cat in 'catenates' $x =~ /cat/; # matches cat in 'housecat' $x =~ /cat/; # matches 'cat' at end of string In the last example, the end of the string is considered a word boundary. Matching this or that We can match different character strings with the alternation metacharacter '|'. To match "dog" or "cat", we form the regex "dog|cat". As before, perl will try to match the regex at the earliest possible point in the string. At each character position, perl will first try to match the first alternative, "dog". If "dog" doesn't match, perl will then try the next alternative, "cat". If "cat" doesn't match either, then the match fails and perl moves to the next position in the string. Some examples: "cats and dogs" =~ /cat|dog|bird/; # matches "cat" "cats and dogs" =~ /dog|cat|bird/; # matches "cat" Even though "dog" is the first alternative in the second regex, "cat" is able to match earlier in the string. "cats" =~ /c|ca|cat|cats/; # matches "c" "cats" =~ /cats|cat|ca|c/; # matches "cats" At a given character position, the first alternative that allows the regex match to succeed will be the one that matches. Here, all the alternatives match at the first string position, so the first matches. Grouping things and hierarchical matching The grouping metacharacters "()" allow a part of a regex to be treated as a single unit. Parts of a regex are grouped by enclosing them in parentheses. The regex "house(cat|keeper)" means match "house" followed by either "cat" or "keeper". Some more examples are /(a|b)b/; # matches 'ab' or 'bb' /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere /house(cat|)/; # matches either 'housecat' or 'house' /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or # 'house'. Note groups can be nested. "20" =~ /(19|20|)dd/; # matches the null alternative '()dd', # because '20dd' can't match Extracting matches The grouping metacharacters "()" also allow the extraction of the parts of a string that matched. For each grouping, the part that matched inside goes into the special variables $1, $2, etc. They can be used just as ordinary variables: # extract hours, minutes, seconds $time =~ /(dd):(dd):(dd)/; # match hh:mm:ss format $hours = $1; $minutes = $2; $seconds = $3; In list context, a match "/regex/" with groupings will return the list of matched values "($1,$2,...)". So we could rewrite it as ($hours, $minutes, $second) = ($time =~ /(dd):(dd):(dd)/); If the groupings in a regex are nested, $1 gets the group with the leftmost opening parenthesis, $2 the next opening parenthesis, etc. For example, here is a complex regex and the matching variables indicated below it: /(ab(cd|ef)((gi)|j))/; 1 2 34 Associated with the matching variables $1, $2, ... are the backreferences "1", "2", ... Backreferences are matching variables that can be used inside a regex: /(www)s1/; # find sequences like 'the the' in string $1, $2, ... should only be used outside of a regex, and "1", "2", ... only inside a regex. Matching repetitions The quantifier metacharacters "?", "*", "+", and "{}" allow us to determine the number of repeats of a portion of a regex we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping that we want to specify. They have the following meanings: o "a?" = match 'a' 1 or 0 times o "a*" = match 'a' 0 or more times, i.e., any number of times o "a+" = match 'a' 1 or more times, i.e., at least once o "a{n,m}" = match at least "n" times, but not more than "m" times. o "a{n,}" = match at least "n" or more times o "a{n}" = match exactly "n" times Here are some examples: /[a-z]+s+d*/; # match a lowercase word, at least some space, and # any number of digits /(w+)s+1/; # match doubled words of arbitrary length $year =~ /d{2,4}/; # make sure year is at least 2 but not more # than 4 digits $year =~ /d{4}|d{2}/; # better match; throw out 3 digit dates These quantifiers will try to match as much of the string as possible, while still allowing the regex to match. So we have $x = 'the cat in the hat'; $x =~ /^(.*)(at)(.*)$/; # matches, # $1 = 'the cat in the h' # $2 = 'at' # $3 = '' (0 matches) The first quantifier ".*" grabs as much of the string as possible while still having the regex match. The second quantifier ".*" has no string left to it, so it matches 0 times. More matching There are a few more things you might want to know about matching operators. In the code $pattern = 'Seuss'; while (<>) { print if /$pattern/; } perl has to re-evaluate $pattern each time through the loop. If $pattern won't be changing, use the "//o" modifier, to only perform variable substitutions once. If you don't want any substitutions at all, use the special delimiter "m''": @pattern = ('Seuss'); m/@pattern/; # matches 'Seuss' m'@pattern'; # matches the literal string '@pattern' The global modifier "//g" allows the matching operator to match within a string as many times as possible. In scalar context, successive matches against a string will have "//g" jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the "pos()" function. For example, $x = "cat dog house"; # 3 words while ($x =~ /(w+)/g) { print "Word is $1, ends at position ", pos $x, " "; } prints Word is cat, ends at position 3 Word is dog, ends at position 7 Word is house, ends at position 13 A failed match or changing the target string resets the position. If you don't want the position reset after failure to match, add the "//c", as in "/regex/gc". In list context, "//g" returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex. So @words = ($x =~ /(w+)/g); # matches, # $word[0] = 'cat' # $word[1] = 'dog' # $word[2] = 'house' Search and replace Search and replace is performed using "s/regex/replacement/modifiers". The "replacement" is a Perl double quoted string that replaces in the string whatever is matched with the "regex". The operator "=~" is also used here to associate a string with "s///". If matching against $_, the "$_ =~" can be dropped. If there is a match, "s///" returns the number of substitutions made, otherwise it returns false. Here are a few examples: $x = "Time to feed the cat!"; $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!" $y = "'quoted words'"; $y =~ s/^'(.*)'$/$1/; # strip single quotes, # $y contains "quoted words" With the "s///" operator, the matched variables $1, $2, etc. are immediately available for use in the replacement expression. With the global modifier, "s///g" will search and replace all occurrences of the regex in the string: $x = "I batted 4 for 4"; $x =~ s/4/four/; # $x contains "I batted four for 4" $x = "I batted 4 for 4"; $x =~ s/4/four/g; # $x contains "I batted four for four" The evaluation modifier "s///e" wraps an "eval{...}" around the replacement string and the evaluated result is substituted for the matched substring. Some examples: # reverse all the words in a string $x = "the cat in the hat"; $x =~ s/(w+)/reverse $1/ge; # $x contains "eht tac ni eht tah" # convert percentage to decimal $x = "A 39% hit rate"; $x =~ s!(d+)%!$1/100!e; # $x contains "A 0.39 hit rate" The last example shows that "s///" can use other delimiters, such as "s!!!" and "s{}{}", and even "s{}//". If single quotes are used "s'''", then the regex and replacement are treated as single quoted strings. The split operator "split /regex/, string" splits "string" into a list of substrings and returns that list. The regex determines the character sequence that "string" is split with respect to. For example, to split a string into words, use $x = "Calvin and Hobbes"; @word = split /s+/, $x; # $word[0] = 'Calvin' # $word[1] = 'and' # $word[2] = 'Hobbes' To extract a comma-delimited list of numbers, use $x = "1.618,2.718, 3.142"; @const = split /,s*/, $x; # $const[0] = '1.618' # $const[1] = '2.718' # $const[2] = '3.142' If the empty regex "//" is used, the string is split into individual characters. If the regex has groupings, then the list produced contains the matched substrings from the groupings as well: $x = "/usr/bin"; @parts = split m!(/)!, $x; # $parts[0] = '' # $parts[1] = '/' # $parts[2] = 'usr' # $parts[3] = '/' # $parts[4] = 'bin' Since the first character of $x matched the regex, "split" prepended an empty initial element to the list. BUGS
None. SEE ALSO
This is just a quick start guide. For a more in-depth tutorial on regexes, see perlretut and for the reference page, see perlre. AUTHOR AND COPYRIGHT
Copyright (c) 2000 Mark Kvale All rights reserved. This document may be distributed under the same terms as Perl itself. Acknowledgments The author would like to thank Mark-Jason Dominus, Tom Christiansen, Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful comments. perl v5.12.1 2010-04-26 PERLREQUICK(1)
All times are GMT -4. The time now is 05:29 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy