Regex Match whole word string in coldfusion

Deadly 提交于 2020-05-13 05:44:05

问题


Im trying this example

first example

keyword = "star"; 
myString = "The dog sniffed at the star fish and growled";
regEx = "\b"& keyword &"\b"; 
if (reFindNoCase(regEx, myString)) { 
     writeOutput("found it"); 
} else { 
     writeOutput("did not find it"); 
} 

Example output -> found it

second example

keyword = "star"; 
myString = "The dog sniffed at the .star fish and growled";
regEx = "\b"& keyword &"\b"; 
if (reFindNoCase(regEx, myString)) { 
     writeOutput("found it"); 
} else { 
     writeOutput("did not find it"); 
}

output -> found it

but i want to find only whole word. punctuation issue for me how can i using regex for second example output: did not find it


回答1:


Coldfusion does not support lookbehind, so, you cannot use a real "zero-width boundary" check. Instead, you can use groupings (and fortunately a lookahead):

regEx = "(^|\W)"& keyword &"(?=\W|$)";

Here, (^|\W) matches either the start of a string, and (?=\W|$) makes sure there is either a non-word character (\W) or the end of string ($).

See the regex demo

However, make sure you escape your keyword before passing to the regex. See ColdFusion 10 now provides reEscape() to prepare string literals for native RE-methods.

Another way is to match spaces or start/end of string:

<cfset regEx = "(^|\s)" & TABLE_NAME & "($|\s)">


来源:https://stackoverflow.com/questions/33960491/regex-match-whole-word-string-in-coldfusion

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