简体   繁体   English

从Java到C#的这段代码正确吗?

[英]Is this code snippet from Java to c# correct?

i'm trying to port some Java stuff to C#. 我正在尝试将一些Java东西移植到C#。 I'm just wondering if the following C# code is the equivalent to the original Java source. 我只是想知道以下C#代码是否等效于原始Java源代码。

Source: Java Code 资料来源:Java代码

private static final Pattern SIMPLE_IDENTIFIER_NAME_PATTERN = 
    Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$");

    private static boolean isValidIdentifier(String s) {
        Matcher m = SIMPLE_IDENTIFIER_NAME_PATTERN.matcher(s);
        return (m.matches() && !reserved.contains(s));
    }

Destination: C# Code 目的地:C#代码

private static readonly Regex SIMPLE_IDENTIFIER_NAME_PATTERN = 
    new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);

private static bool IsValidIdentifier(string s)
{
    Match match = SIMPLE_IDENTIFIER_NAME_PATTERN.Match(s);
    return (match.Success && !Reserved.Contains(s));
}

Cheers :) 干杯:)

根据我的评论,我认为您应该编写一个或多个单元测试以验证端口是否按预期工作。

看起来不错,但是为什么不从移植单元测试开始呢?

Your use of the Caret and Dollar indicates that you want to match embedded newlines in the subject string, as opposed to the beginning and end of the entire string. 您使用插入符号和美元表示您要匹配主题字符串中嵌入的换行符,而不是整个字符串的开头和结尾。 If so, then you should definitely set the RegexOptions.Multiline option for your Regex. 如果是这样,那么您绝对应该为Regex设置RegexOptions.Multiline选项。 If you do not set that option, your Caret and Dollar will have no special implication. 如果您未设置该选项,则您的Caret和Dollar将没有特殊含义。

private static readonly Regex SIMPLE_IDENTIFIER_NAME_PATTERN = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled | RegexOptions.Multiline);

It may also be worthwhile to evaluate the need for compiling this Regex. 评估是否需要编译此Regex也可能是值得的。 Does it need to be used repeatedly (such as, in a loop) ? 是否需要重复使用(例如,循环使用)? If not, then your Regex will in fact have lower performance. 如果没有,那么您的Regex实际上将具有较低的性能。

Besides this point, your conversion appears to be valid. 除此之外,您的转换似乎有效。 As some of the others have suggested, the only way to be reasonably sure is to unit test it. 正如其他一些人所建议的那样,唯一可以合理确定的方法是对其进行单元测试。

Beware that a readonly type is not immutable. 注意只读类型不是不可变的。 That means that you cannot change which reference of regex you point to, but you can change the regex object itself. 这意味着您不能更改指向的正则表达式的引用,但是可以更改正则表达式对象本身。 (Luckily the contract on the regex won't let you change the expression though) (幸运的是,正则表达式上的合同不允许您更改表达式)

Beware that .Net regex syntax is not the same as *nix regex syntax, so you may get bitten there. 请注意,.Net regex语法与* nix regex语法不同,因此您可能会被咬伤。 Confirm as per the MSDN docs what you need your string to do: 根据MSDN文档,确认您需要字符串来执行以下操作:

MSDN Regex Syntax MSDN正则表达式语法

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

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