There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
>>> help(str.find)
Help on method_descriptor:
find(...)
S.find(sub [,start [,end]]) -> int
Thus, we can build it ourselves:
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) # use start += 1 to find overlapping matches
list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]
No temporary strings or regexes required.
I'd like to find all occurrences of a substring while ignore some characters. How can I do it in Python?
Example:
long_string = 'this is a t`es"t. Does the test work?' small_string = "test" chars_to_ignore = ['"', '`'] print(find_occurrences(long_string, small_string))
should return [(10, 16), (27, 31)] because we want to ignore the presence of chars ` and ".
-
(10, 16)is the start and end index of t`es"t inlong_string, -
(27, 31)is the start and end index oftestinlong_string.
Python Regex: Extract all occurences of a substring within a string - Stack Overflow
How can I find all exact occurrences of a string, or close matches of it, in a longer string in Python?
Python regex when string contains any word from a list of words AND any word from another list
Use lookaheads. ^(?=.*foo|.*bar|.*Python)(?=.*me|.*you|.*we)
Add \b around the words (e.g. \bfoo\b) if you want them as isolated words, otherwise you get matches like fool)
https://regex101.com/r/dnqSjr/1
More on reddit.comhow to extract only names in string by using regex
You may use this regex:
r"\d+['\"]?x\d+['\"]?(?:\s*[a-zA-Z]+)?"
RegEx Demo
Code:
>>> import re
>>> line = "The dimensions of the first rectangle: 10'x20', second rectangle: 10x35cm, third rectangle: 30x35cm"
>>> print (re.findall(r"\d+['\"]?x\d+['\"]?(?:\s*[a-zA-Z]+)?", line))
["10'x20'", '10x35cm', '30x35cm']
RegEx Details:
\d+: Match 1+ digits['\"]?: Match optional'or"x: Match letterx\d+: Match 1+ digits['\"]?: Match optional'or"(?:\s*[a-zA-Z]+)?: Match optional units comprising 1+ letters
You can do this without regex using split:
In [1089]: m = [i.split(':')[1].strip() for i in line.split(',')]
In [1090]: m
Out[1090]: ["10'x20'", '10x35cm', '30x35cm']
Goal:
-
I'd like to find all exact occurrences of a string, or close matches of it, in a longer string in Python.
-
I'd also like to know the location of these occurrences in the longer string.
-
To define what a close match is, I'd like to set a threshold, e.g. number of edits if using the edit distance as the metric.
-
I'd also like the code to give a matching score (the one that is likely used to determine if a candidate substring is over the matching threshold I set).
How can I do so in Python?
Example:
long_string = """1. Bob likes classical music very much. 2. This is classic music! 3. This is a classic musical. It has a lot of classical musics. """ query_string = "classical music"
I'd like the Python code to find "classical music" and possibly "classic music", "classic musical" and "classical musics" depending on the string matching threshold I set.
Research: I found Checking fuzzy/approximate substring existing in a longer string, in Python? but the question focuses on the best match only (i.e., not all occurrences) and answers either also focuses on the best match or don't work on multi-word query strings (since the question only had a single-word query strings, or return some incorrect score (doesn't get a perfect score even for an exact match).