Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Other Programming Languages (http://www.programmingforums.org/forum38.html)
-   -   Keywords regex (http://www.programmingforums.org/showthread.php?t=14071)

titaniumdecoy Oct 1st, 2007 1:15 AM

Keywords regex
 
I'm having trouble coming up with a simple regular expression. I want a regex that will match a list of keywords, which must be surrounded by non-word characters (\W+). However, if two keywords are next to each other, the \W at the end of the first is "used up" by the first keyword and causes the next keyword not to match because of the \W at the beginning. For example:

:

\W+(void|int)\W+
will match only "void" in the string

:

void int
Any ideas? I am using PCRE. Is there a flag I can set, or something else I can do?

glimmy Oct 17th, 2007 6:14 PM

Re: Keywords regex
 
Perhaps using the global flag would help, and maybe using the word boundary anchors (\b) instead. They start the pattern matching at the beginning of the word instead. How you capture the result can also affect the results.

For Example:
:

/\b(void|int)\b/g

titaniumdecoy Oct 17th, 2007 6:30 PM

Re: Keywords regex
 
Thanks, glimmy. That does the trick. As it happens, I had already found a solution to this problem which I posted here yesterday; unfortunately, it was erased this morning as result of server issues. However, I prefer your solution to mine as it is much simpler (although both work equally well). Here is mine, which uses lookaround constructs:

:

(?<=\W|^)(void|int)(?=\W|$)


All times are GMT -5. The time now is 2:52 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC