使用正则表达式在两个特殊字符之间获取字符串 [英] Fetch string between two special character using regex
本文介绍了使用正则表达式在两个特殊字符之间获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有字符串
-aaa-bbb-ccc-ddd-eee-fff-ggg-hhh-iii-jjj-kkk-lll-
我想使用正则表达式在 - 这个特殊字符之间取字符串。
我使用了以下代码;这是代码片段。
正则表达式r =新正则表达式(@ - (。+?) - );
MatchCollection mc = r.Matches(name);
但它不起作用。请帮我解决这个问题。
提前谢谢。
解决方案
从我的观点来看,使用正则表达式是一种工程矫枉过正。事实上,正则表达式是针对字符串的复杂操作而设计的,并且在分隔符(或特殊字符,在您调用它)之间获取文本不被视为复杂操作。所有主要框架(基本上99%的所有语言)都提供了一个字符串类,它还提供了一种通过分隔符分割字符串的方法。
在C#中,你可以在下面实现你想要的方式:
使用系统;
public class SplitTest {
public static void Main(){
string yourString = - aaa-bbb-ccc- ddd-eee-fff-ggg-hhh-iii-jjj-kkk-lll -
string [] split = words.Split( new Char [] {' - ' },StringSplitOptions.RemoveEmptyEntries); // 设置分隔符列表,空条目()是已移除
foreach ( string s in split){
Console.WriteLine(s);
}
}
}
// 该示例显示以下内容输出到控制台:
// aaa
// bbb
// < span class =code-comment> ccc
// ddd
// eee
// fff
// ggg
// hhh
// jjj
// kkk
// lll
(小于?= - )(?= - )[A-ZA-Z] +
try @ - ?(。+?) - 所以patern可以重叠
There is the string
-aaa-bbb-ccc-ddd-eee-fff-ggg-hhh-iii-jjj-kkk-lll-
I want to fetch string between "-" this special character using regex.
I've used this following code; here is the code snippet.
Regex r = new Regex(@"-(.+?)-"); MatchCollection mc = r.Matches(name);
But it's not working. Please help me to solve this.
Thanks in advance.
解决方案
From my point of view, using a regular expression is an engineering overkill. Fact is that regular expressions were designed for complex operations on strings, and getting the text between a separator (or "special character", as you call it) is not considered a complex operation. All of the major frameworks which (basically 99% of all languages) provide a string class also provide a method to split a string by a separator.
In C#, you can achieve what you want in the following way:
using System; public class SplitTest { public static void Main() { string yourString= "-aaa-bbb-ccc-ddd-eee-fff-ggg-hhh-iii-jjj-kkk-lll-" string [] split = words.Split(new Char [] {'-'}, StringSplitOptions.RemoveEmptyEntries);//set your list of separators, Empty entries ("") are removed foreach (string s in split) { Console.WriteLine(s); } } } // The example displays the following output to the console: // aaa // bbb // ccc // ddd // eee // fff // ggg // hhh // jjj // kkk // lll
(?<=-)[a-zA-Z]+(?=-)
try @"-?(.+?)-" so the patern can overlap
这篇关于使用正则表达式在两个特殊字符之间获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文