简体   繁体   中英

match regex between varying number of characters

The following regex matches "EXAMPLETEXT" in my example below but I'd like to be able to use \\d* to match one or more digits instead of \\d\\d . Is that possible or is there a better method?

String:

09.04.EXAMPLETEXT.14

Regex:

(?<=\.\d\d\.)(.*)(?=\.)

You can't use * or + or ? quantifiers inside lookbehind assertions in perl,java,python regexes (they won't support variable length lookbehind). But you can use those symbols inside lookbehind in c# family.

If your're on php or perl, you may use \\K

\.\d*\.\K(.*)(?=\.)

Another hack in all languages is, just print all the captured chars.

\.\d*\.(.*)\.

Example for greedy:

>>> s = "09.043443.EXAMPLETEXT.14"
>>> re.search(r'\.\d*\.(.*)\.', s).group(1)
'EXAMPLETEXT'

Example for non-greedy match:

>>> re.search(r'\.\d*\.(.*?)\.', s).group(1)
'EXAMPLETEXT'

Use negated char class.

>>> re.search(r'\.\d*\.([^.]*)\.', s).group(1)
'EXAMPLETEXT'

You don't need to use lookbehind at all for this, a regex such as this would work:

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

https://regex101.com/r/pP6lX7/1

Or if you want to be able to match the string inside some other text

(?:\d+\.)+([^\s]*)(?:\.\d+)+

https://regex101.com/r/sB5mB2/1

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