且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用正则表达式拆分括号内用逗号分隔的字符串

更新时间:2023-02-26 09:42:10

老实说,我会用两个正则表达式:第一个提取逗号分隔值,这非常简单:

(?< = xyz\()。+?(?= \))



然后用逗号分割字符串,或用第二个简单的正则表达式解析它:

([^ ,] +?)(?=,| 


Wich为您提供单独匹配中的每个元素。



这样,laters更改是一个更容易解决的整个负载 - 复杂的正则表达式难以阅读甚至更难修改!


非正则表达式解决方案,不优雅,但是......



 string s =message(hello){message = msg.hello;} xyz('Text1','Text2 ',Text3); asdgfd main.send(msg); ; 

var parts = s.Split(new string [] {xyz(,);},StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Contains( ,))
.SelectMany(x => x.Split(new string [] {,},StringSplitOptions.RemoveEmptyEntries))
.ToList();


My Input String :
"message(hello) {message= msg.hello;}xyz('Text1','Text2', Text3);asdgfd main.send(msg);"

Output:

'Text1'
'Text2'
Text3

I need to match "xyz('Text1','Text2', Text3)" from the above string and need to get each word separated by a comma(,) within the bracket. Can anyone give the proper regex to do this?

What I have tried:

I have tried but cannot able to get that separated values properly

To be honest with you, I'd do it with two regexes: the first to extract the comma separated values, which is pretty trivial:
(?<=xyz\().+?(?=\))


Then either Split the string on commas, or parse it with a second, simple regex:

([^,]+?)(?=,|


)

Wich gives you each element in a separate Match.

That way, laters changes are a whole load easier to work out - complex regexes are hard to read and even harder to modify!


Non-regex solution, not elegant, but...

string s = "message(hello) {message= msg.hello;}xyz('Text1','Text2', Text3);asdgfd main.send(msg);";

var parts = s.Split(new string[]{"xyz(", ");"}, StringSplitOptions.RemoveEmptyEntries)
	.Where(x=>x.Contains(","))
	.SelectMany(x=>x.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries))
	.ToList();