1

I am looking for a specific string in text, and want to get it only if found.

I can write it as followד and it works:

if re.search("Counter=(\d+)", line):
  total = int(re.search("Counter=(\d+)", line).group(1))
else:
  total = 1

But I remember another nicer way to write it with question mark before the "group", and put value "1" as default value in case of re.search return an empty result.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Avi_dev
  • 23
  • 5
  • *question mark before something* that's not Python – iBug Jun 30 '22 at 11:33
  • 1
    Do you mean `int(re.search("Counter=(\d+)", line)?.group(1))`? that's C# syntax, and will check for `null(None)` value only. You could define `total = 1` before the `if` and drop the `else`. – Guy Jun 30 '22 at 11:33
  • Does this help? if total := int(re.search("Counter=(\d+)", line).group(1)) total = 1 – toyota Supra Jun 30 '22 at 11:38

3 Answers3

1

Assuming you are using Python 3.8 or later, you can assign to the output of re.search in the if statement with the walrus-operator :=.

if match := re.search("Counter=(\d+)", line):
   total = int(match.group(1))
else:
   total = 1

If you want a oneliner:

total = int(match.group(1)) if (match := re.search("Counter=(\d+)", line)) else 1
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • I had Python 3.7.4 and I upgraded it to latest python, but vsCode still thinks my python is the older release. How can I fix it? (in windows cmd "python --version" displays the latest python release. – Avi_dev Jun 30 '22 at 12:11
  • I found that I can select the python 3.10 via "view" -> command pallet, but now there is a new problem:import xlsxwriter and pandas doesn't work :( – Avi_dev Jun 30 '22 at 12:17
  • For legacy Python (below 3.8) see the [findall with ternary](https://stackoverflow.com/a/72815661/5730279) implementation. – hc_dev Jun 30 '22 at 12:21
  • @אלישבע you can still use the same code if you use another line to assign `match = re.search("Counter=(\d+)", line)` beforehand. – timgeb Jun 30 '22 at 12:23
  • @אלישבע the problem in your comment here is simple - by changing the version you don't have libraries installed for other versions. Simply install again for the proper Python (pip) version – Tomerikoo Jun 30 '22 at 13:17
0

When using re.findall it will return a list with groups or empty. Then you can conditionally assign based on this list using a ternary expression:

counters = re.findall("Counter=(\d+)", line)
total = counters[0] if counters else 1

(This will also work in Python before 3.8.)

Test with both cases:

counters = re.findall("Counter=(\d+)", 'Hello World')
total = counters[0] if counters else 1
print(total)
# 1

counters = re.findall("Counter=(\d+)", 'Counter=100')
total = counters[0] if counters else 1
print(total)
# 100
hc_dev
  • 8,389
  • 1
  • 26
  • 38
-1

You could match the empty end and replace by 1 then:

total = int(re.search("Counter=(\d+)|$", line)[1] or 1)

Try it online!

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65