简体   繁体   English

C#正则表达式,通过引用字符串提取字符串

[英]C# Regex, extract strings by reference string

Edit: Solution by @Heinzi https://stackoverflow.com/a/1731641/87698 编辑:@Heinzi提供的解决方案https://stackoverflow.com/a/1731641/87698


I got two strings, for example someText-test-stringSomeMoreText? 我有两个字符串,例如someText-test-stringSomeMoreText? and some kind of pattern string like this one {0}test-string{1}? 还有某种模式字符串,例如一个{0}test-string{1}? .

I'm trying to extract the substrings from the first string that match the position of the placeholders in the second string. 我正在尝试从第一个字符串中提取与第二个字符串中的占位符位置匹配的子字符串。

The resulting substrings should be: someText- and SomeMoreText . 产生的子字符串应为: someText-SomeMoreText

I tried to extract with Regex.Split("someText-test-stringSomeMoreText?", "[.]*test-string[.]*\\?" . However this doesn't work. 我尝试使用Regex.Split("someText-test-stringSomeMoreText?", "[.]*test-string[.]*\\?"提取。但这是行不通的。

I hope somebody has another idea... 我希望有人有另一个主意...

One option you have is to use named groups: 您拥有的一种选择是使用命名组:

(?<prefix>.*)test-string(?<suffix>.*)\?

This will return 2 groups containing the wanted prefix and the suffix. 这将返回2组,其中包含所需的前缀和后缀。

var match = Regex.Match("someText-test-stringSomeMoreText?", 
    @"(?<prefix>.*)test-string(?<suffix>.*)\?");
Console.WriteLine(match.Groups["prefix"]);
Console.WriteLine(match.Groups["suffix"]);

I got a solution, at least its a bit dynamical. 我有一个解决方案,至少它有点动态。

First I split up the pattern string {0}test-string{1}? 首先,我拆分模式字符串{0}test-string{1}? with string[] patternElements = Regex.Split(inputPattern, @"(\\\\\\{[a-zA-Z0-9]*\\})"); 使用string[] patternElements = Regex.Split(inputPattern, @"(\\\\\\{[a-zA-Z0-9]*\\})");

Then I spit up the input string someText-test-stringSomeMoreText? 然后我吐出输入字符串someText-test-stringSomeMoreText? with string[] inputElements = inputString.Split(patternElements, StringSplitOptions.RemoveEmptyEntries); 使用string[] inputElements = inputString.Split(patternElements, StringSplitOptions.RemoveEmptyEntries);

Now the inputElements are the text pieces corresponding to the placeholders {0},{1},... 现在, inputElements是对应于占位符{0},{1},...的文本片段{0},{1},...

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

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