简体   繁体   English

正则表达式查找和删除具有特定模式的字符

[英]Regex to find and remove char with specific pattern

I have this string我有这个字符串

This is mail@mail.text #1 but page is @001# 

(001 is variable, ex 01a or 021 etc) (001 是可变的,例如 01a 或 021 等)

And I want to make it我想成功

This is mail@mail.text #1 but page is 001

With this ^@([0-9]{1,3})#\\z i can find a string that starts with "@" and ends with "#" with max 3 chars inside but it doesn't match inside a entire text.有了这个^@([0-9]{1,3})#\\z我可以找到一个以“@”开头并以“#”结尾的字符串,里面最多有 3 个字符,但它在整个内部不匹配文本。

You need to remove ^ (start of the string anchor) and replace the match with the contents of Group 1 using $1 backreference:您需要删除^ (字符串锚点的开头)并使用$1反向引用将匹配替换为 Group 1 的内容:

var str = "This is mail@mail.text #1 but page is @001#";
var result = Regex.Replace(str, @"@([0-9]{1,3})#\z", "$1");

See the regex demo查看正则表达式演示

The @([0-9]{1,3})#\\z pattern will find @ , 1 to 3 digits (put inside a group), and then a # at the very end of string ( \\z ).@([0-9]{1,3})#\\z图案会发现@ ,1至3位数(放入一个组内),然后将#在字符串(非常结束\\z )。

Another variation: if the value may start with a digit and can be followed with an ASCII letter or digit, use另一种变体:如果值可能以数字开头并且可以跟随着 ASCII 字母或数字,请使用

var result = Regex.Replace(str, @"@([0-9][0-9a-zA-Z]{0,2})#\z", "$1");

And if the value can just be alphanumeric, just use如果该值只能是字母数字,只需使用

var result = Regex.Replace(str, @"@([0-9a-zA-Z]{1,3})#\z", "$1");

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

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