C# 使用指令匹配
我有几个类需要格式化。我需要将using指令放在名称空间中。换句话说,我必须改变:C# 使用指令匹配,c#,.net,regex,C#,.net,Regex,我有几个类需要格式化。我需要将using指令放在名称空间中。换句话说,我必须改变: // some comment about system using System; using System.Collections.Generics; // needed to create lists namespace MyNamespace { ... code 进入: 因此,简而言之,我希望能够匹配: 到目前为止,我使用的是这个正则表达式:(?s)(//.*(?=\r))(\r\n |
// some comment about system
using System;
using System.Collections.Generics; // needed to create lists
namespace MyNamespace
{
... code
进入:
因此,简而言之,我希望能够匹配:
到目前为止,我使用的是这个正则表达式:
(?s)(//.*(?=\r))(\r\n | ^)*使用。*代码>
第一组(//.*(?=\r))(\r\n |^)
与注释匹配。因此,如果使用有一个评论,我想采取的意见也。请注意,我在组的末尾放置了一个*
,以便有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
{
- 逐行读取文件
- 如果该行以
/
开头(可能在空格之后),请记住它(它是注释)
- 多行注释(
/*
到*/
)更为棘手
- 如果行以
开头,请使用
,记住它
- 如果行以
名称空间
开头,则打印它,打印所有记住的行,然后打印其余的行
您真的需要正则表达式吗?为什么不使用纯字符串函数呢?您只需在
名称空间
之前使用
指令查找注释和,然后将它们移到名称空间后面(可能还有缩进)
比如:
// 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
{
- 逐行读取文件
- 如果该行以
/
开头(可能在空格之后),请记住它(它是注释)
- 多行注释(
/*
到*/
)更为棘手
- 如果行以
开头,请使用
,记住它
- 如果行以
名称空间
开头,则打印它,打印所有记住的行,然后打印其余的行
尝试regex(?s)(//[^\n\r]*)\s*?*((使用[^;]+;)\s*?)+
尝试regex((//[^\n\r]*)\s*?)*((使用[^;]+;)\s*?)+
如果您在哪里有类似的东西:
// 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语句。如果您希望在何处拥有以下内容:
// 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语句。挑剔:这些是using指令,而不是using语句。这些声明是用来处理资源的。好主意,谢谢。我认为这应该是一个答案…吹毛求疵:这些是使用指令,而不是使用语句。这些声明是用来处理资源的。好主意,谢谢。我认为这应该是一个答案。。。