正则表达式识别字符串只是有特殊字符和空格Regex for identifying strings which just has special character and a white spaces

- 此内容更新于:2015-01-06
主题:

我试图找出一个字符串是否包含|和一个空白,没有别的在c#中使用一个正则表达式。 我试着以下表达式但这并不确定到底和它所有的记录。 不继续扩展的列表。 提前感谢任何帮助。 谢谢, vj

原文:

I trying to find out whether a string just contains | and a white space and nothing else in it using a regex in c#. I tried the below expression but that does not identify exactly and it gets all the records which are falling out.

Regex reg = new Regex("^[^a-zA-Z0-9@#!.]+$");

The list of not keeps on extending. Thanks in advance for any help on this.

Thanks, VJ

Jerry的回复:你的描述和正则表达式不# 39;t相当匹配的意义。如果你想获得一个匹配字符串只包含空格和|或如果你想获得一个匹配字符串包含甚至1空间或| ?

(原文:Your description and your regex don't quite match in meaning. Are you trying to get a match if the string contains only spaces and | or are you trying to get a match if the string contains even 1 space or |?)

解决方案:
如何使用下面的直接目标你想匹配,而不是你不想匹配: 一个故障: ^ -字符串的开始 […)-有下列: s -空格字符 | - - -文字| *重复任意次(包括0次) 美元的字符串
原文:

How about using the following to directly target what you want to match instead of what you don't want to match:

new Regex(@"^[s|]*$");

A breakdown:

  • ^ - start of string
  • [...] - any of the following:
    • s - whitespace character
    • | - literal |
  • * repeated any number of times (including 0 times)
  • $ end of string
vijay kumar的回复:谢谢,,我试着表达但不*。我能知道什么区别。

(原文:Thanks that worked, i tried that expression but not with *. Can I please know what difference does that make.)

JLRishe的回复:没有*,表达式只匹配字符串包含一个空格字符或|。

(原文:Without the *, the expression would only match a string consisting of one whitespace character or |.)