简体   繁体   English

C#正则表达式中的“ Enter”问题

[英]“Enter” issue in Regex of C#

There I have an issue on regex expression in C#, Code: 我在C#中的正则表达式表达式上有一个问题,代码:

// For 1D barcode scanner
Regex regex = new Regex("^(.*)\x0D$", RegexOptions.Compiled);
var match = regex.Match("1234\r");

The match.Success is true. 比赛成功是真的。 Then I change the code as following: 然后,我将代码更改如下:

 // For 2D barcode scanner
 Regex regex = new Regex("^(.*)$", RegexOptions.Compiled);
 var match = regex.Match("1234\r");

The match.Success is still true(Expect false). match.Success仍然为true(期望为false)。 I don't know where is error. 我不知道哪里出错了。

Actually, the string "1234\\r" is a result of a 1D barcode scanner, the suffix of 1D barcode scanner is "\\x0D" in my software, but the suffix of 2D barcode scanner is null in my software.I think it must be something wrong on regex expression for 2D barcode. 实际上,字符串“ 1234 \\ r”是一维条形码扫描仪的结果,一维条形码扫描仪的后缀在我的软件中为“ \\ x0D”,但二维条形码扫描仪的后缀在我的软件中为空。我认为必须2D条码的正则表达式表达有问题。

With default settings, $ is interpreted as the end of the input string, rather than the end of a line. 在默认设置下, $被解释为输入字符串的末尾,而不是一行的末尾。 This will allow your .* to match against any trailing whitespace that might be added. 这将使您的.*与可能添加的任何尾随空白匹配。

If you wish to exclude this, you can do so with a character class, like this ^([^\\r]*)$ 如果您希望排除这种情况,可以使用字符类,例如^([^\\r]*)$

I use another work round for this case, code as bellow: 在这种情况下,我使用另一轮工作,代码如下:

 if (string.IsNullOrEmpty(Prefix) && string.IsNullOrEmpty(Suffix))  
    regex = new Regex("^[a-z0-9!\"#$%&'()*+,.\\/:;<=>?@\\[\\] ^_`{|}~-]*$", RegexOptions.Compiled);
 else
     {
       regex = new Regex($"^{this.Prefix}(.*){this.Suffix}$", RegexOptions.Compiled);
     }

It means that if the suffix and prefix is null or empty, I use a regex to match "all printable charters". 这意味着如果后缀和前缀为null或为空,我将使用正则表达式来匹配“所有可打印的章程”。

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

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