简体   繁体   English

C#正则表达式明确匹配字符串

[英]C# Regex explicitly match string

I want to match only words from AZ and az with an optional period at the end. 我只想匹配来自AZ和az的单词,最后加上一个可选的句点。 This is the code I have so far: 这是我到目前为止的代码:

return Regex.IsMatch(word, @"[A-Za-z]\.?")

This means the following should return true: test , test. 这意味着以下内容应返回true: testtest. .

The following should return false: t3st , test.. , . 以下应返回false: t3sttest... , .

Right now this regex returns true for everything. 现在,此正则表达式对所有内容都返回true。

Try this regex : 试试这个regex

@"^[A-Za-z]+\.?$"

Boundary matchers 边界匹配器

  • ^ means beginning of a line ^表示行首
  • $ means end of a line $表示行尾

Greedy quantifier 贪婪的量词

  • [A-Za-z]+ means [A-Za-z], one or more times [A-Za-z] +表示[A-Za-z],一次或多次

Your regex only asks for a single letter followed by an optional period. 您的正则表达式只要求输入一个字母,后跟一个可选的期间。 Since all your words start with a letter, that regex returns true. 由于您所有的单词都以字母开头,因此该正则表达式将返回true。

Notice the + in Prince John Wesley's answer - that says to use one or more letters, so it'll "eat" all the letters in the word, stopping at a non-letter. 请注意,John Wesley王子的答案中的+号表示使用一个或多个字母,因此它将“吃掉”单词中的所有字母,并以非字母开头。 Then the \\.? 然后是\\。? tests for an optional period. 测试一个可选的时期。

I don't think the ^ and $ are needed in this case. 我认为在这种情况下不需要^和$。

You might also want to include the hyphen and the single-quote in your regex; 您可能还希望在正则表达式中包括连字符和单引号。 otherwise you'll have problems with hyphenated words and contractions. 否则,您会遇到连字和紧缩字的问题。

That may get messy; 可能会变得凌乱; some words have more than one hyphen: "port-of-call" or "coat-of-arms", for example. 某些单词具有多个连字符:例如,“呼叫端口”或“纹章”。 Very rarely you'll find a word with more than one quote: "I'd've" for "I would have". 很少有人会找到一个引号多的单词:“我会”表示“我会”。 They're rare enough you can probably forget about 'em. 它们非常罕见,您可能会忘记它们。 (oops! there's a word that starts with a quote... :) (糟糕!有一个以引号开头的单词... :)

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

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