开发者

regular expression for a word

开发者 https://www.devze.com 2023-03-12 01:21 出处:网络
I am doing a string parsing problem in PHP. I want a regular expression fo开发者_开发技巧r a word in a dictionary. The word can contain only A-Z and a-z. I came up with this regex but this seems to be

I am doing a string parsing problem in PHP. I want a regular expression fo开发者_开发技巧r a word in a dictionary. The word can contain only A-Z and a-z. I came up with this regex but this seems to be not working. Can someone help.

$regexp = "/[A-z]+/";
if(preg_match($regexp,$buffer)){    
   print $buffer . "<BR>";
}

Adding rkt's comment for eadibility

currently using this regex

$regexp = "/[A-Za-z]+/";

but still lot of irrelevant words are getting printed , for eg .

a.new,#quickbar a.new{color:#ba0000} enwiki:resourceloader:filter:minify-css:5:f2a9127573a22335c2a9102b208c73e7 wgNamespaceNumber=0;
wgAction="view";
wgPageName="Roger_Federer";
wgMainPageTitle="‌​Main Page";
wgWikimediaMobileUrl="http:\/\/en.m.wikipedia.org\/wiki";
document.writeln("\x3cdiv id=\"localNotice\"\x3e\x3cp\x3e\x3c/p\x3e\n\x3c/div\x3e");


If you want to match a whole word only...

/\b[A-Z]+\b/i


Besides the problem that Limo Wan Kenobi noted, your regex doesn't do what you think it does.

/[A-Za-z]+/

All this checks is that a letter, either case, appears somewhere in the input. If your input looks like this:

1111112222222333333333A333333444444555555567

It will still match.

What you are looking for is this regular expression:

/^[A-Za-z]+$/

This will match the beginning of the string, then one or more letters, and finally the end of the string. Now, there's no room for anything except letters!


your regex should be

$regexp = "/[A-Za-z]+/";


You might check my answer to How do you split a javascript string by spaces and punctuation? which contains JavaScript which can be used to break English text into an array of words and punctuation, where words can be hyphenated (well-defined) or compound (won't).


The regex should be /\b[A-Za-z]+\b/, thought for matching words in a dictionary you probably want something more restrictive than that since words can't usually have caps at any odd location.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号