1

我有几个需要格式化的类。我需要将 using 指令放在命名空间内。换句话说,我必须改变:

// some comment about system
using System;
using System.Collections.Generics; // needed to create lists

namespace MyNamespace
{
     ... code

进入:

namespace MyNamespace
{

     // some comment about system
     using System;
     using System.Collections.Generics; // needed to create lists

     ... code

所以简而言之,我希望能够匹配:

// some comment about system
using System;
using System.Collections.Generics; // needed to create lists

到目前为止我所做的是这个正则表达式:(?s)(//.*?(?=\r))(\r\n|^)*using .*?;

第一组(//.*?(?=\r))(\r\n|^)匹配评论。因此,如果用户有评论,我也愿意接受该评论。请注意,我*在组的末尾放置了一个 0 或更多评论。由于某种原因,第二次使用不匹配,为什么?

4

3 回答 3

1

尝试正则表达式(?s)((//[^\n\r]*)\s*?)*((using [^;]+;)\s*?)+

于 2012-07-18T15:34:08.313 回答
0

你真的需要正则表达式吗?为什么不使用纯字符串函数?您只需要using在 a 之前找到注释和指令namespace,然后将它们移到它后面(可能还有缩进)。

就像是:

  • 逐行读取文件
  • 如果该行以//(可能在空格之后)开头,请记住它(这是注释)
  • 多行注释(/*to */)比较棘​​手。
  • 如果该行以 开头using,请记住它
  • 如果该行以 开头namespace,则打印它,打印所有记住的行,然后打印其余行。
于 2012-07-18T15:27:15.813 回答
0

如果你在哪里有类似的东西:

// comment goes here
using System.Text.RegularExpressions; // for regexes
using System.Text; /* comment */
using System.Collections.Generic; // som comment
   /* this is a long comment
       that spans multiple lines
       in order to explain this using */
using System.Foo;




namespace EncloseCodeInRegion
{

正则表达式:

(((//.*?\r\n)|( */\*[\s\S]*?\*/))?(\r\n)? *using .+?;(( *//.*(?=\r))|( */\*[\s\S]*?\*/))?)(?=[\s\S]*?namespace)

将匹配所有 using 语句。

于 2012-07-18T15:43:40.043 回答