简体   繁体   中英

Regular Expression to find the exact match of the string

Hi I have records like

MicroAlgae 7.5
AlgaeSerum 6.5
Algae 1.5

Here i need to extract the value of algae that is 1.5 and it should not extract the values of microalgae and algaeserum. I have used the regex as

/(?!Micro)/Algae,
Algae\s*/^(!Serum)/,
\\bAlgae\\b

Kindly let me know how can I write the regex according to that

If you have some large text where you need to pull the number from, you may use a simple regex with a capturing group around the part you need to extract:

import re
s = """MicroAlgae 7.5
AlgaeSerum 6.5
Algae 1.5"""
m = re.search(r'\bAlgae\s+([0-9.]+)', s)
if m:
    print(m.group(1))

See the Python demo

The [0-9.]+ may be replaced with a more precise [0-9]+(?:\\.[0-9]+)? .

Details :

  • \\b - the leading word boundary
  • Algae - the literal char sequence Algae
  • \\s+ - one or more whitespaces
  • ([0-9.]+) - Group 1: one or more digits or dots or
  • [0-9]+(?:\\.[0-9]+)? - 1+ digits ( [0-9]+ ), followed with an optional sequence of a . ( \\. ) and 1+ digits ( [0-9]+ ).

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