简体   繁体   中英

Perl Regex to get a substring between two of the same characters

给定一些字符串originalString = "#SomeWord# More words" ,我希望能够从originalString获得子字符串"SomeWord"

my $substr = (split /#/, $originalString)[1];

/#([^#]+)#/ works for me.

Some syntax notes:

  • // delimiter characters marking the start and end of the regexp
  • # literal hash mark
  • [] a character class

Explanation of the regexp above:

  • [^#] any character that isn't a hash mark
  • [^#]+ one or more such characters
  • ([^#]+) a capturing group of the above

In this case, the regexp looks for any non-# characters between two #'s. Here's a full example:

my $foo = "#SomeWord# More words";

if ($foo =~ /#([^#]+)#/) {
    print "$1\n";
} else {
    print "no match\n";
}

You can also use regular expressions:

$originalString=~ /\#([^#]+)\#/;
# Now $1 holds your required string

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