简体   繁体   English

正则表达式设置单词字符并匹配确切的单词

[英]Regex setting word characters and matching exact word

I need my C# regex to only match full words, and I need to make sure that +-/*() delimit words as well (I'm not sure if the last part is already set that way.) I find regexes very confusing and would like some help on the matter. 我需要我的C#正则表达式仅匹配完整的单词,并且我还需要确保+-/ *()分隔单词(我不确定最后一部分是否已经设置成这种方式。)我发现正则表达式非常令人困惑并希望对此有所帮助。 Currently, my regex is: 目前,我的正则表达式是:

public Regex codeFunctions = new Regex("draw_line|draw_rectangle|draw_circle");

Thank you! 谢谢! :) :)

Try 尝试

public Regex codeFunctions = new Regex(@"\b(draw_line|draw_rectangle|draw_circle)\b");

The \\b means match a word boundary, ie a transition from a non-word character to a word character (or vice versa). \\b表示匹配单词边界,即从非单词字符到单词字符的转换(反之亦然)。

Word characters include alphabet characters, digits, and the underscore symbol. 文字字符包括字母字符,数字和下划线符号。 Non-word characters include everything else, including +-/*() , so it should work fine for you. 非单词字符包含所有其他内容,包括+-/*() ,因此它对您来说应该可以正常工作。

See the Regex Class documentation for more details. 有关更多详细信息,请参见Regex类文档

The @ at the start of the string makes the string a verbatim string , otherwise you have to type two backslashes to make one backslash. 字符串开头的@使该字符串成为逐字字符串 ,否则必须键入两个反斜杠以使一个反斜杠。

Do you want to match any words, or just the words listed above? 您要匹配任何单词,还是仅匹配上面列出的单词? To match an arbitrary word, substitute this for the bit that creates the Regex object: 要匹配任意单词,请将其替换为创建Regex对象的位:

new Regex (@"\b(\w+)\b");

In the future, if you want more characters to be treated as whitespace (for example, underscores), I would recommend String.Replace-ing them to a space character. 将来,如果希望将更多字符视为空格(例如,下划线),我建议使用String。将它们替换为空格字符。 There may be a clever way to get the same effect with regular expressions, but personally I think it would be too clever. 使用正则表达式可能会有一种巧妙的方法来获得相同的效果,但是我个人认为这太聪明了。 The String.Replace version is obvious. String.Replace版本很明显。

Also, I can't help but recommend that you read up on regular expressions. 另外,我不禁建议您阅读正则表达式。 Yes, they look like line noise until you get used to them, but once you do they're convenient and there are plenty of good resources out there to help you. 是的,在您习惯它们之前,它们看起来像是线路噪音,但是一旦您习惯了它们,它们就会很方便,并且有很多好的资源可以为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM