简体   繁体   English

如何从REGEX的捕获组中排除具有特殊字符的特定单词?

[英]How to exclude particular word with special character from a capture group in REGEX?

I want to create Regex for below text: 我想为以下文本创建正则表达式:

date=2016-02-25 time=10:14:22+0000

In this we need to capture like below(Single Capture Group) 在这种情况下,我们需要像下面这样捕获(单个捕获组)

2016-02-25 10:14:22

I have tried below Regex but i cannot able to achieve my O/P: 我已经在正则表达式下面尝试过,但是我无法实现我的O / P:

^(?!time=)\D+(\d{4}\-\d+\-\d+\s\D+\d+\:\d+\:\d+) 

Is it possible to create Regex? 是否可以创建正则表达式? Please help me on this. 请帮帮我。 Thanks in advance! 提前致谢!

Try this 尝试这个

.*?((?:\d+-?)+).*?((?:\d+\:?)+).*

Regex demo 正则表达式演示

Explanation: 说明:
. : Any character except line break sample :除换行符示例外的任何字符
* : Zero or more times sample *样品零次或多次
? : Once or none sample :一次或不一次样品
( … ) : Capturing group sample ( … ) :捕获团体样本
(?: … ) : Non-capturing group sample (?: … ) :非捕获组样本
\\ : Escapes a special character sample \\ :逃避特殊字符样本
+ : One or more sample + :一个或多个样本

You could just capture both date and time with separate groups and join them together using Python's string operators: 您可以使用单独的组捕获日期和时间,然后使用Python的字符串运算符将它们连接在一起:

import re

text = 'date=2016-02-25 time=10:14:22+0000'
pattern = r'^date=(\d{4}-\d{2}-\d{2}) time=(\d{2}:\d{2}:\d{2})[+-]\d{4}$'

match = re.match(pattern, text.strip())
result = " ".join(match.groups())

print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM