正则表达式挑战:将不同规则分组为仅两个组。

huangapple go评论102阅读模式
英文:

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 ?

因为你没有回复,我将为pythonphp提供一个正则表达式:

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"

huangapple
  • 本文由 发表于 2017年4月28日 09:14:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/43670383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定