How to extract upper case words within a long string using perl

余生长醉 提交于 2020-01-06 07:06:08

问题


I am trying to find a way to extract only upper case words (at least three consecutive upper characters, plus numbers) from quite a long string using perl.

Example:

"Hello world, thank GOD it's Friday, I can watch EPISODE4" 

Output:

"GOD EPISODE4"

For some reason I cannot come up with a sensible way to do this, any ideas? Thanks!


回答1:


Use character classes:

my @matches = ( $string =~ /\b[[:upper:]|[:digit:]]{3,}+\b/g );
say join " - ", @matches;

(You stated uppercase characters and numbers. You didn't specify where the number would be. You also didn't say whether or not I need to do something with the number.

Edit your question to include other requirements).




回答2:


This will get you any upper case words that are over 3 characters and which may or may not have numbers at the end:

my $str = "Hello world, thank GOD its Friday, I can watch EPISODE4"; 
my @matches = ($str =~ /\b([A-Z]{3,}+[0-9]*)\b/g);

You can modify it to look for upper case characters after the numbers:

my @matches = ($str =~ /\b([A-Z]{3,}+[0-9]*[A-Z]*)\b/g);


来源:https://stackoverflow.com/questions/23415808/how-to-extract-upper-case-words-within-a-long-string-using-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!