简体   繁体   English

C# 正则表达式匹配最后一个下划线后的最后一位数字

[英]C# Regex match the last digit after the last underscore

Using regex I'm trying to get only the last digit (can be only 2 or 3) after the last underscore.使用正则表达式,我试图只获取最后一个下划线后的最后一位数字(只能是 2 或 3)。

What I have right now is getting the digit and characters.我现在拥有的是获取数字和字符。 I need to cut off the characters and only get the digit [2-3].我需要切断字符,只得到数字 [2-3]。

Here is my example -- I need to get only 2 after the last underscore.这是我的例子——我只需要在最后一个下划线后得到 2。 Currently getting both digit and characters当前同时获取数字和字符

ABC_0000_DEFG_1I_23_45_HIJKL2.pdf
The output I want -- 2 (after HIJKL).

^.*_\K[^.]+

If I get rid of ^ with \d, d{2-3}, ... it still gets HIJKL.

You can use您可以使用

_[^_]*(\d)[^_]*$

Which matches the last underscore, followed by a digit surrounded by anything but underscores.它与最后一个下划线匹配,后跟一个被除下划线以外的任何东西包围的数字。

You can use [23] instead of \\d if you want to ignore anything other than 2 or 3 .如果您想忽略23以外的任何内容,您可以使用[23]而不是\\d

The regular expression正则表达式

_[^_]*([2-3])[^_]*$

should do you.应该做你。 It matches:它匹配:

  • _ — an underscore, followed by _ — 下划线,后跟
  • [^_]* — zero or more characters other than underscore, followed by [^_]* — 除下划线外的零个或多个字符,后跟
  • ([23]) — the decimal digits 2 or 3 , followed by ([23]) — 十进制数字23 ,后跟
  • [^_]* — zero or more characters other than underscore, followed by [^_]* — 除下划线外的零个或多个字符,后跟
  • $ — end-of-text $ — 文本结束

You will need to get match group #1:您将需要获得匹配组 #1:

var rx = new Regex(@"_[^_]*([2-3])[^_]*$");
var m  = rx.Match("ABC_0000_DEFG_1I_23_45_HIJKL2.pdf");
var s  = m.Success ? m.Groups(1) : null;

At which point, s should be "2".此时, s应为“2”。

To get a match only in .NET you might also use lookarounds:要仅在 .NET 中进行匹配,您还可以使用环视:

(?<=_[^_]*)[23](?=[^_]*$)

The pattern matches:模式匹配:

  • (?<=_[^_]*) Positive lookbehind, assert _ followed by optional chars other than _ (?<=_[^_]*)正向后视,断言_后跟除_以外的可选字符
  • [23] Match either 2 or 3 [23]匹配 2 或 3
  • (?=[^_]*$) Positive lookahead to assert no _ till the end of the string (?=[^_]*$)正向前瞻断言没有_直到字符串的末尾

See a .NET regex demo or a C# demo .请参阅.NET regex 演示C# 演示

Example code示例代码

Regex regex = new Regex(@"(?<=_[^_]*)[23](?=[^_]*$)");
Match match = regex.Match("ABC_0000_DEFG_1I_23_45_HIJKL2.pdf");
if (match.Success)
{
    Console.WriteLine(match.Value);
}

Output输出

2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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