正则表达式去除除给定字符之外的字符
本文关键字:字符 正则表达式 | 更新日期: 2023-09-27 18:36:27
我想去掉字符串,但只留下以下内容:
[a-zA-Z]+[_a-zA-Z0-9-]*
我正在尝试输出以字符开头的字符串,然后可以包含字母数字、下划线和破折号。如何使用正则表达式或其他函数执行此操作?
因为正则表达式第二部分的所有内容都在第一部分中,所以您可以执行以下操作:
String foo = "_-abc.!@#$5o993idl;)"; // your string here.
//First replace removes all the characters you don't want.
foo = Regex.Replace(foo, "[^_a-zA-Z0-9-]", "");
//Second replace removes any characters from the start that aren't allowed there.
foo = Regex.Replace(foo, "^[^a-zA-Z]+", "");
因此,首先将其缩减为仅允许的字符。然后删除任何不能出现在开头的允许字符。
当然,如果您的正则表达式变得更加复杂,此解决方案很快就会崩溃。
假设你在集合中有字符串,我会这样做:
- 对于集合中的每个元素,请尝试匹配正则表达式
- 如果 !success,则从集合中删除字符串
或者反过来 - 如果匹配,则将其添加到新集合中。
如果字符串不在集合中,您可以添加有关输入外观的更多详细信息吗?
如果你想提取所有与正则表达式匹配的标识符,你可以这样做:
var input = " _wontmatch f_oobar0 another_valid ";
var re = new Regex( @"'b[a-zA-Z][_a-zA-Z0-9-]*'b" );
foreach( Match match in re.Matches( input ) )
Console.WriteLine( match.Value );
使用 MatchCollection matchColl = Regex.Matches("input string","your regex");
然后使用:
string [] outStrings = new string[matchColl.Count]; //A string array to contain all required strings
for (int i=0; i < matchColl.Count; i++ )
outStrings[i] = matchColl[i].ToString();
您将在 outString 中拥有所有必需的字符串。希望这有帮助。
编辑
var s = Regex.Matches(input_string, "[a-z]+(_*-*[a-z0-9]*)*", RegexOptions.IgnoreCase);
string output_string="";
foreach (Match m in s)
{
output_string = output_string + m;
}
MessageBox.Show(output_string);