为什么当期望 0 到 4 位数字时,Regex.IsMatch 对于换行符作为输入返回 true?

问题描述 投票:0回答:1

我正在尝试验证一些用户输入的电话号码的国家/地区代码。国家/地区代码是可选的,但当它包含值时,它应该是 1 到 4 位数字。我写了一个正则表达式,并期望在 C# 中传递

"\n"
时正则表达式会失败。它似乎匹配,因此我在 Visual Studio 2022(版本 17.8.6)中打开 C# 交互式控制台。事实上,该模式意外地匹配了换行符。我的实验如下:

Microsoft (R) Visual C# Interactive Compiler version 4.8.0-7.23572.1 ()
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> using System.Text.RegularExpressions;
> Regex.IsMatch("\n", "^[0-9]{0,4}$")
true
> Regex.IsMatch("\n", "^[0-9]{0,4}$", RegexOptions.Multiline)
true
> Regex.IsMatch("\n", "^[0-9]{0,4}$", RegexOptions.Singleline)
true
> Regex.IsMatch("\n", "^[0-9]{0,4}$", RegexOptions.None)
true
> Regex.IsMatch("\n", "^[0-9]{0,4}$", RegexOptions.IgnorePatternWhitespace)
true
> Regex.IsMatch("\n", "^\\d{0,4}$")
true

C#交互控制台截图:

Screenshot of the C# interactive console in Visual Studio 2022 showing that a newline matches a digits-only regular expression.

出于好奇,我打开了 Google Chrome 控制台并输入了以下 JavaScript:

let pattern = /^\d{0,4}$/
undefined
pattern.test("\n")
false
pattern = /^[0-9]{0,4}$/
pattern.test("\n")
false

Chrome 截图:

Screenshot of Google Chrome testing the same regular expression and showing that it doesn't match.

这绝对让我摸不着头脑。

为什么

Regex.IsMatch
报告换行符匹配(行首);零个或多个数字; (行尾)当给定带有单个换行符的字符串时 -
"\n"

c# regex
1个回答
0
投票

您使用的模式

^[0-9]{0,4}$
匹配 0-4 次数字,并且还会匹配空字符串。

对于 C#,有一个关于“字符串或行结尾:$”的 描述

$ 锚指定前面的模式必须出现在 输入字符串的末尾或之前 在输入字符串的末尾。

对于 JavaScript,有一个关于使用锚点 ^

$
description

如果设置了 m 标志,... 和 $ 也匹配,如果字符到 右边是行终止符。

对于 C#,它可以匹配换行符之前的空字符串,对于 JavaScript,如果设置了

m
标志,则可以。

const pattern1 = /^[0-9]{0,4}$/;
console.log(pattern1.test("\n"));

const pattern2 = /^[0-9]{0,4}$/m;
console.log(pattern2.test("\n"));

© www.soinside.com 2019 - 2024. All rights reserved.