简体   繁体   中英

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:

^(?!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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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