[英]regex split string by specific values
Trying to split a string by specific characters and values with a regex expression.尝试使用正则表达式按特定字符和值拆分字符串。
I have the following string for example:例如,我有以下字符串:
abc.def.ghi:wxyz_1234
I would like to get both ' wxyz ' and ' 1234 '.我想同时获得“ wxyz ”和“ 1234 ”。
ie the string between ':' and '_' and the string after '_'即':'和'_'之间的字符串和'_'之后的字符串
Cheers!干杯!
Maybe,也许,
([^\s:_]+)_(\S+)
might work OK.可能工作正常。
With lookbehind, to create a left boundary for pre-underscore string:使用lookbehind,为前下划线字符串创建左边界:
(?<=:)([^_]+)_(.+)
import re
string = '''
abc.def.ghi:wxyz_1234
abc.def.ghi:abcd_78910
abc.def.ghi: foo_baz123
'''
expression = r'([^\s:_]+)_(\S+)'
for i in re.findall(expression, string):
print(i[0])
print(i[1])
wxyz
1234
abcd
78910
foo
baz123
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com .如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板上进行了解释。 If you'd like, you can also watch in this link , how it would match against some sample inputs.
如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。
string str = "abc.def.ghi:wxyz_1234";
Regex rx = new Regex(":(.*)_(.*)");
Match match = rx.Match(str);
string first =match.Groups[1].Value;
string second= match.Groups[2].Value;
I managed to create the following Case A - (?<=:)(.+)(?=_)
Case B - (?<=_).*
我设法创建了以下案例 A -
(?<=:)(.+)(?=_)
案例 B - (?<=_).*
Guess the options are endless...猜猜选项是无止境的......
Thanks for your assistance!感谢你的协助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.