我有如下所示的正则表达式:
Regex rx1 = new Regex(@"<div>/\*(.(?!\*/))*\*/(</div>|<br/></div>|<br></div>)");
Regex rx2 = new Regex(@"/\*[^>]+?\*/(<br/>|<br>)");
Regex rx3 = new Regex(@"/\*[^>]+?\*/");
任何人都可以帮助加入正则表达式成为1模式吗?
答案 0 :(得分:1)
你对RX1的问题是由(.(?!\*/))*\*/
引起任何字符的零次或多次捕获,因为*/
后面的答案永远不会匹配。
更新回答
@"(?'div'<div>)?/\*((?<!\*/).)*?\*/(?:<br/?>)?(?'-div'</div>)?(?(div)(?!))"
这将捕获:
(?'div'<div>) an optional opening div stored in capture group div /\* char sequence /* ((<!\*/).)*? zero or more characters, non greedy and each character is not preceded by the string */ \*/ char sequence `*/` (?:<br/?>)? optionally <br> or <br/> (?'-div'</div>)? optionally </div> remove from capture group `div` (?(div)(?!)) match only if capture group div is empty (ie balanced <div> </div>)
答案 1 :(得分:0)
我认为你需要这个来组合模式:
(pattern1|pattern2|pattern3)
表示pattern1 or pattern2 or pattern3
答案 2 :(得分:0)
尝试以下(这是frankenstein代码,但它可以帮助您管理每个正则表达式变量,因为它是自己的,而不是将所有三个连接成一个大的正则表达式(尽管它没有错,但可能很难管理正则表达式的更改) :
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BatchRegex
{
class Program
{
static void Main(string[] args)
{
string[] target =
{
"<div>/*...*/</div> <div>/*...*/<br></div> <div>/*...*/<br></div>",
"/*...*/<br></div> or /*...*/<br/></div>"
};
foreach (var tgt in target)
{
var rx1 = new Regex[]{new Regex(@"<div>/\*(.(?!\*/))*\*/(</div>|<br/></div>|<br></div>)", RegexOptions.Multiline),
new Regex(@"/\*[^>]+?\*/(<br/>|<br>)", RegexOptions.Multiline),
new Regex(@"/\*[^>]+?\*/", RegexOptions.Multiline)};
foreach (var rgx in rx1)
{
var rgxMatches = rgx.Matches(tgt).Cast<Match>();
Parallel.ForEach(rgxMatches, match =>
{
Console.WriteLine("Found {0} in target {1}.", match, tgt);
});
}
}
Console.Write("Press any key to exit...");
Console.ReadKey();
}
}
}