简体   繁体   中英

How to match regex with special characters ",( in C#

I generated following string after reading file.

"The approach of neural computing is to capture the guiding principles that underly the brain's solution to these problems and apply them to computer systems." ( :14 ) "1.2 THE STRUCTURE OF THE BRAIN" ( :16 ) "brain at a low level. It contains approximately ten thousand million (10") basic units, called neurons. Each of these neurons is connected to about ten thousand (lo4) others." ( :16 )

What pattern I want to match looks like this: "string" ( :digit+ )

Its output will be:

The approach of neural computing is to capture the guiding principles that underly the brain's solution to these problems and apply them to computer systems.
1.2 THE STRUCTURE OF THE BRAIN
brain at a low level. It contains approximately ten thousand million (10") basic units, called neurons. Each of these neurons is connected to about ten thousand (lo4) others.

I am new to regular expression. I have used

var reg = new Regex("\".*?\"");

It can match content within double quotation but how i can match rest of pattern?

It helps to break this down into what you want the regex to do. Since you want to capture different groups, you'd surround them in parentheses:

You want to match on:

a quote
followed by anything that isn't a quote, one or more times; capture this as a group
followed by a quote
followed by parentheses
followed by colon
followed by a number, one or more times
followed by parentheses

string reg = "\"([^\"]+)\" \\( :\\d+ \\)"

if I understand it correct, you need to detect all ( :digit )

string regex = "(\()(.){1}(:)[1-9]{1,}(.){1}(\))"

you can try it here: http://regexr.com/

  @ allows putting quotes in a string. So you can use this
  in regex search pattern.

  var st = @" ""1.2 THE STRUCTURE OF THE BRAIN"" (:15) )";

            List<string> result = new List<string>
                                (Regex.Matches(st, @" ""\d+\.\d+[\w\s]+""\s+\(:\d+\)")
                                .Cast<Match>()
                                .Select(x => x.Value)
                                .ToList());

            //  "1.2 THE STRUCTURE OF THE BRAIN" (:15)

    ""\d+\.\d+[\w\s]+"" ===>  "1.2 THE STRUCTURE OF THE BRAIN"
    \s+\(:\d+\)         ===>  (:15)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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