regex 使用正则表达式获取C#文件字段和属性

doinxwow  于 2023-06-25  发布在  C#
关注(0)|答案(1)|浏览(108)

我想匹配(从.cs文件中选择)属性名,字段名和使用正则表达式的地方。
这是示例类:

using System;
... // usings
using Grpc.Net.Client;
using UI = Gtk.Builder.ObjectAttribute;

namespace DummyProject;

public class MainWindow : Window
{
    [UI] private readonly MenuItem _aboutMenuItem;
    [UI] private readonly MenuItem _openFolderItem;
    [UI] private readonly MenuItem _openFileItem;
    [UI] private readonly Viewport _fileViewport;
    [UI] private readonly Notebook _codeNotebook;
    private readonly SourceView _codeSourceView;
    private readonly FileViewer _fileViewer;
    private readonly Files.FilesClient _filesClient;
    
    public FileSystemViewer FileSystemViewer { get; }
    
    public MainWindow() 
    {
        _fileViewer = new FileViewer();
        // some code
    }

    // methods

结果将是:_aboutMenuItem_openFolderItem_openFileItem_fileViewport_codeNotebook_codeSourceView_fileViewer_filesClientFileSystemViewer
我试过这个正则表达式:^(?:(?=[^()]*$))?(?:(?!.*\b(namespace|return|using|class)\b))[\t \b]*(?:[\[\]a-zA-Z0-9_.]+\s+)?(?:(?:private|public|protected|internal)\s+)?(?:(?:static readonly|static|const|readonly|volatile|virtual|override)\s+)?(?:(?:[a-zA-Z0-9\.]+)\s+)?(\w+)\s*
但此正则表达式匹配不正确(请参见https://regex101.com/r/ZbctGa/3
有什么建议吗?

f8rj6qna

f8rj6qna1#

您可以使用以下命令捕获 * properties * 和 * field *。

(?:public|private)(?! class) (?:readonly )?(?:.+?) (.+?)[ ;]

输出量

_aboutMenuItem
_openFolderItem
_openFileItem
_fileViewport
_codeNotebook
_codeSourceView
_fileViewer
_filesClient
FileSystemViewer

相关问题