简体   繁体   中英

C# Regex match on special characters

I know this stuff has been talked about a lot, but I'm having a problem trying to match the following...

Example input: "test test 310-315"

I need a regex expression that recognizes a number followed by a dash, and returns 310. How do I include the dash in the regex expression though. So the final match result would be: "310".

Thanks a lot - kcross

EDIT: Also, how would I do the same thing but with the dash preceding, but also take into account that the number following the dash could be a negative number... didnt think of this one when I wrote the question immediately. for example: "test test 310--315" returns -315 and "test 310-315" returns 315.

Regex regex = new Regex(@"\d+(?=\-)");

\\d+ - Looks for one or more digits

(?=\\-) - Makes sure it is followed by a dash

The @ just eliminates the need to escape the backslashes to keep the compiler happy.

Also, you may want this instead:

\d+(?=\-\d+)

This will check for a one or more numbers, followed by a dash, followed by one or more numbers, but only match the first set.


In response to your comment , here's a regex that will check for a number following a - , while accounting for potential negative (-) numbers:

Regex regex = new Regex(@"(?<=\-)\-?\d+");

(?<=\\-) - Negative lookbehind which will check and make sure there is a preceding -

\\-? - Checks for either zero or one dashes

\\d+ - One or more digits

(?'number'\\d+)- will work ( no need to escape ). In this example the group containing the single number is the named group 'number' . if you want to match both groups with optional sign try:

@"(?'first'-?\d+)-(?'second'-?\d+)"

See it working here . Just to describe, nothing complicated, just using -? to match an optional - and \\d+ to match one or more digit. a literal - match itself.

here's some documentation that I use:

http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

in the comments section of that page, it suggests escaping the dash with '\\-'

make sure you escape your escape character \\

You would escape the special meaning of - in regex language (means range) using a backslash (\\) . Since backslash has a special meaning in C# literals to escape quotes or be part of some characters, you need to escape that with another backslash(\\) . So essentially it would be \\d+\\\\- .

\\b\\d*(?=\\-) you will want to look ahead for the dash

\\b = is start at a word boundry \\d = match any decimal digit * = match the previous as many times as needed (?=\\-) = look ahead for the dash

Edited for Formatting issue with the slash not showing after posting

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