如何使用正则表达式拆分括号内用逗号分隔的字符串 [英] How to split string separated by a comma within the bracket using regex

查看:673
本文介绍了如何使用正则表达式拆分括号内用逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入字符串:

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



输出:



'Text1'

'Text2'

Text3



我需要从上面的字符串中匹配xyz('Text1','Text2',Text3)并需要获取每个字符串括号内的逗号(,)分隔的单词。任何人都可以给出正确的正则表达式吗?



我尝试过的事情:



我已经尝试但无法正确获取分离的值

解决方案

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

(?< = 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();


这篇关于如何使用正则表达式拆分括号内用逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆