英文:
regex challenge to group different rules into only two groups
问题
我有以下数据:
msg=hello msg=hellohello age: s35 { getAge } for name=peter id="123"
我想使用正则表达式将它们分类到以下的组1(冒号左边)和组2(冒号右边)的结构中:
msg : hello
msg : hello/hello
age : thirtyfive { getAge } for
name: peter'
id : "123"
我想到了以下的正则表达式:
([^,=\s]*)=([^,\s]*)|([^= ]*): ([^=]*for)
这个正则表达式可以完成任务,但我有一个不幸的限制。我只能允许两个正则表达式组。正如你所看到的,"age"属性和相应的键分别在第3组和第4组。
如何在正则表达式中将它们全部分组到只有两个组中?
英文:
I have the following data:
msg=hello msg=hellohello age: s35 { getAge } for name=peter id="123"
I would like to use regex to classify them in the following group 1 (left of the colon) and group 2 (right of the colon) structure:
msg : hello
msg : hello/hello
age : thirtyfive { getAge } for
name: peter'
id : "123"
I come up with the following regular expression
([^,=\s]*)=([^,\s]*)|([^= ]*): ([^=]*for)
This does the job except that I have an unfortunate constraint. I can only allow two regular expression groups. As you can see the "age" attribute and corresponding key are in group 3 and group 4, correspondingly.
How can I group them all in just two groups in regex?
答案1
得分: 0
你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。以下是要翻译的内容:
> which programing language are you using ?
因为你没有回复,我将为python
和php
提供一个正则表达式:
PYTHON:
import re
result = re.sub(r"([a-z]+)(?:=|:\s+)(\d+.*?for |[^ ]+)", "\: \\n", original, 0, re.IGNORECASE | re.DOTALL | re.MULTILINE)
PHP:
$result = preg_replace('/([a-z]+)(?:=|:\s+)(\d+.*?for |[^ ]+)/sim', ': \n', $original);
输出:
msg: hello
msg: hellohello
age: 35 { getAge } for
name: peter
id: "123"
英文:
> which programing language are you using ?
Because you didn't reply, I'll provide a regex for python
and php
:
PYTHON:
import re
result = re.sub(r"([a-z]+)(?:=|:\s+)(\d+.*?for |[^ ]+)", "\: \\n", original, 0, re.IGNORECASE | re.DOTALL | re.MULTILINE)
PHP:
$result = preg_replace('/([a-z]+)(?:=|:\s+)(\d+.*?for |[^ ]+)/sim', ': \n', $original);
Output:
msg: hello
msg: hellohello
age: 35 { getAge } for
name: peter
id: "123"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论