Python re.error: look-behind requires fixed-width pattern 해결Python re.error: look-behind requires fixed-width pattern Fix
파이썬 re 에서 look-behind requires fixed-width pattern 을 만난 독자가 원인이 되는 두 모양을 알아보고 캡처 그룹 패턴으로 바꿔 같은 값을 얻게 한다.
룩비하인드 안의 | 갈래 길이가 다르거나 \s* 같은 수량자가 있으면 3.9·3.12·3.14 모두 같은 문구로 거부했다. 앞부분을 (?:...) 로 소비하고 원하는 값만 (...) 하나로 꺼내면 앞 일치와 겹치지 않는 입력에서 같은 값이 나왔다.
오류가 난 패턴에서 룩비하인드 괄호를 지우고 앞부분을 (?:...) 로, 꺼낼 값을 (...) 하나로 바꾼 뒤 findall 결과가 예전 기대값과 같은지 샘플 한 줄로 대조한다.
목차
한 줄 요약:
look-behind requires fixed-width pattern은 룩비하인드 안쪽 길이가 하나로 정해지지 않을 때 나므로, 앞부분을(?:...)로 읽고 값만(...)로 꺼낸다.
바로 할 것: re.findall(r"(?<=USD |US\$)\d+", text) 를 re.findall(r"(?:USD |US\$)(\d+)", text) 로 바꾼다. 앞부분은 (?:...) 로 묶어 패턴이 직접 읽어 들이게(소비하게) 하고, 꺼낼 값만 괄호 하나 (...) 에 둔다.
import re
text = "주문 USD 120, 환불 US$45, 배송 EUR 7"
re.findall(r"(?:USD |US\$)(\d+)", text) # ['120', '45']
오류는 이렇게 보인다
re.compile 이나 re.findall 이 패턴을 만드는 순간 예외가 나고 마지막 줄은 이렇다. 시험한 3.9·3.12 는 re.error, 3.14 는 re.PatternError 였고 공식 문서는 3.13 부터 이름이 바뀌었다고 적는다. 문구는 같다.
re.error: look-behind requires fixed-width pattern
re.PatternError: look-behind requires fixed-width pattern
공식 문서가 3.13 에서 PatternError 가 원래 error 였고 error 는 호환 별칭으로 남았다고 적는다. 그래서 except re.error 는 3.14 에서도 이 예외를 잡았다.
원인 1: 룩비하인드 안 | 갈래의 길이가 다르다
룩비하인드 (?<=...) 는 “지금 위치 바로 앞이 이 패턴과 맞는가”를 보되 그 글자를 결과에 넣지 않는 문법이다. 공식 문서는 안쪽 패턴이 고정된 길이의 문자열에만 맞아야 한다고 적고, abc 와 a|b 는 되고 a* 와 a{3,4} 는 안 된다고 예를 든다. a|b 는 두 갈래가 둘 다 한 글자라서 되는 것이다.
USD 는 4글자, US$ 는 3글자다. 두 갈래를 한 룩비하인드에 넣으면 거부된다.
아래 -> 오른쪽은 실제 출력을 줄여 적은 것이다.
(?<=USD |US\$)\d+ -> look-behind requires fixed-width pattern
(?<=USD|US\$ )\d+ -> 같은 오류 (USD 3글자, US$ 와 공백 4글자)
(?<=USD|EUR)\s\d+ -> 통과: [' 120', ' 7']
(?<=ab|cd)x -> 통과
갈래 길이가 모두 같으면 | 를 써도 통과한다. 갈래 하나하나를 룩비하인드로 따로 두는 (?:(?<=USD )|(?<=US\$))\d+ 도 ['120', '45'] 를 냈다.
원인 2: \s* 같은 수량자가 들어 있다
공백이 몇 칸일지 모르니 \s* 를 넣고 싶어지는 자리다. 로그 한 줄이 price: 300 qty:2 price:45 일 때 (?<=price:\s*)\d+ 는 같은 오류로 거부됐다. 길이가 정해지지 않았기 때문이다. 공백 길이에 상한이 없을 때는 갈래마다 룩비하인드를 따로 두는 방법으로 풀리지 않는 자리다.
처방: 앞부분을 소비하고 값만 그룹으로 꺼낸다
룩비하인드는 앞부분을 결과에서 빼 주려고 쓴다. 같은 효과를 앞부분을 일반 패턴으로 소비한 다음 값만 괄호로 꺼내는 방식으로 얻는다. 길이가 달라도 수량자가 있어도 일반 패턴은 제약이 없다.
re.findall(r"(?:USD |US\$)(\d+)", text) # ['120', '45']
re.findall(r"price:\s*(\d+)", log) # ['300', '45']
규칙은 둘이다. 앞부분은 (?:...) 로 묶어 그룹으로 세지 않게 하고, 꺼낼 값은 괄호 하나에만 둔다. re.findall 은 그룹이 하나면 그 그룹의 문자열 목록을 주기 때문이다. 괄호를 빼면 앞부분까지 들어간 전체 일치가 나온다. 반대로 괄호가 둘 이상이면 튜플 목록이 나온다.
re.findall(r"(?:USD |US\$)\d+", text) # ['USD 120', 'US$45'] <- 값만이 아님
re.findall(r"(USD |US\$)(\d+)", text) # [('USD ', '120'), ('US$', '45')]
문자열을 바꾸는 re.sub 에서는 앞부분을 지워 버리지 않게 그룹 번호로 되살린다.
re.sub(r"(USD |US\$)(\d+)", r"\g<1>[\2]", text)
# '주문 USD [120], 환불 US$[45], 배송 EUR 7'
자주 부딪히는 세 모양을 바꿔 보기
같은 방식이 통하는 흔한 패턴 셋이다. 입력은 각각 한 줄이고 세 파이썬 모두 아래 결과가 같았다. 앞의 두 줄은 원인 1과 같은 갈래 길이 문제이고, 셋째는 ? 가 길이를 정하지 못하게 하는 문제다.
| 이전(오류) | 이후 | 입력 | 이후 결과 |
|---|---|---|---|
(?<=id=|uid=)\d+ |
(?:id=|uid=)(\d+) |
id=7 uid=42 |
['7', '42'] |
(?<=^|,)\w+ |
(?:^|,)(\w+) |
a,b,c |
['a', 'b', 'c'] |
(?<=https?://)[\w.]+ |
https?://([\w.]+) |
http://a.com https://b.com |
['a.com', 'b.com'] |
둘째 줄의 ^ 는 길이가 0이고 , 는 1이라 갈래 길이가 달라진다. 맨 앞 값과 쉼표 뒤 값을 한 패턴으로 잡을 때 자주 나오는 모양이다.
앞부분이 앞의 일치와 겹칠 때
소비하는 방식은 룩비하인드와 똑같지는 않다. 1,2,3 에서 숫자 앞의 숫자, 를 조건으로 삼을 때 룩비하인드 (?<=\d,)\d+ 는 ['2', '3'] 을 냈지만 소비하는 \d,(\d+) 는 ['2'] 만 냈다. 이 글의 해석은 1,2 가 한 번에 읽히면서 3 앞의 2 가 이미 쓰였기 때문이라는 것이다. 앞부분에 길이가 다른 갈래가 있고 앞의 일치와 겹칠 수 있는 입력이라면, 갈래마다 룩비하인드를 따로 둔다. 1,2, 3 에서 (?:(?<=\d,)|(?<=\d, ))\d+ 는 ['2', '3'] 을, 소비하는 \d,\s*(\d+) 는 ['2'] 만 냈다.
겹침과 \s* 가 함께 필요한 자리는 표준 re 의 룩비하인드((?<=\d,\s*)\d+)가 같은 오류로 거부된다. 그 자리는 다음 절의 regex 모듈이 ['2', '3'] 을 냈다.
다른 길: regex 모듈과 Node
서드파티 regex 모듈(2026.11.19)을 pip 로 깔면 원래 패턴 (?<=USD |US\$)\d+ 가 그대로 ['120', '45'] 를 냈고 (?<=\d,\s*)\d+ 도 통과했다. 표준 라이브러리만 쓰는 스크립트라면 위 처방이 의존성을 늘리지 않는다. 같은 패턴은 Node v26.7.0 의 정규식(다른 언어는 시험하지 않았다)에서도 오류 없이 ['120', '45'] 를 냈다.
시험 범위와 한계
macOS 26.6.2 arm64 에서 시스템 파이썬 3.9.6, Homebrew 파이썬 3.12.13·3.14.7 로 시험했고 시험 전체를 두 번 실행해 출력이 같았다. 갈래 길이가 다른 |, \s*, 부정형 (?<!...) 는 오류 문구를, 길이가 같은 | 는 통과 결과를 확인했다. 3.13 자체는 설치하지 않았고 PatternError 이름은 3.14 와 공식 문서로만 확인했다. 겹침 사례는 1,2,3 과 1,2, 3 두 입력만 보았다. 부정형은 같은 오류가 나는 것만 확인했고 처방은 다루지 않았다. Windows·Linux·PyPy, 대용량 입력의 속도, regex 모듈의 다른 버전은 시험하지 않았다. 표의 세 줄은 입력 한 줄씩만 보았다. 샘플 문자열은 직접 만든 한 줄이라 실제 로그 파일이나 다른 문자 구성의 입력은 보지 않았다.
세 줄 요약
- 파이썬 re 의 룩비하인드는 안쪽 길이가 하나여야 해서, 길이가 다른
|갈래와\s*는look-behind requires fixed-width pattern으로 거부된다. - 룩비하인드를 지우고 앞부분을
(?:...)로 소비해 값만(...)하나로 꺼내면, 앞부분이 앞 일치와 겹치지 않는 입력에서 같은 값이 나온다. - 서드파티
regex모듈은 원래 패턴이 그대로 통과했지만, 표준 라이브러리만 쓴다면 캡처 그룹 처방이면 된다.
Help a reader who hit look-behind requires fixed-width pattern in Python re recognize the two shapes that cause it and rewrite the pattern with a capture group to get the same values.
When a lookbehind held | branches of different lengths or a quantifier such as \s*, Python 3.9, 3.12 and 3.14 all rejected it with the same message. Consuming the prefix with (?:...) and pulling out just the value with one (...) gave the same values on inputs where the prefix does not overlap the previous match.
In the failing pattern, remove the lookbehind parentheses, write the prefix as (?:...) and the value as one (...), then compare the findall result with the old expected values on one sample line.
Contents
- What the error looks like
- Cause 1: the | branches inside the lookbehind have different lengths
- Cause 2: a quantifier such as \s* is inside
- The fix: consume the prefix and pull out only the value in a group
- Rewriting three common shapes
- When the prefix overlaps the previous match
- Another route: the regex module and Node
- Test scope and limits
- Three-line summary
One-line summary:
look-behind requires fixed-width patternappears when the inside of a lookbehind does not have one fixed length, so read the prefix with(?:...)and pull out only the value with(...).
What to do now: Change re.findall(r"(?<=USD |US\$)\d+", text) to re.findall(r"(?:USD |US\$)(\d+)", text). Wrap the prefix in (?:...) so the pattern reads it directly (consumes it), and put only the value you want in a single pair of parentheses (...).
import re
text = "주문 USD 120, 환불 US$45, 배송 EUR 7"
re.findall(r"(?:USD |US\$)(\d+)", text) # ['120', '45']
What the error looks like
The exception is raised the moment re.compile or re.findall builds the pattern, and the last line looks like this. Python 3.9 and 3.12, which were tested, raised re.error; 3.14 raised re.PatternError, and the official documentation says the name changed in 3.13. The message is the same.
re.error: look-behind requires fixed-width pattern
re.PatternError: look-behind requires fixed-width pattern
The official documentation says PatternError was originally named error in 3.13 and that error stays as a backward-compatible alias. That is why except re.error also caught this exception on 3.14.
Cause 1: the | branches inside the lookbehind have different lengths
A lookbehind (?<=...) checks that “what comes right before this position matches this pattern” without putting those characters in the result. The official documentation says the inner pattern may only match strings of some fixed length, and gives abc and a|b as allowed and a* and a{3,4} as not allowed. a|b works because both branches are one character long.
USD is 4 characters and US$ is 3. Putting both branches into one lookbehind gets rejected.
The right side of each -> below is the real output, shortened.
(?<=USD |US\$)\d+ -> look-behind requires fixed-width pattern
(?<=USD|US\$ )\d+ -> same error (USD is 3 characters, US$ and a space is 4)
(?<=USD|EUR)\s\d+ -> passes: [' 120', ' 7']
(?<=ab|cd)x -> passes
When all branches have the same length, | passes. Putting each branch into its own lookbehind, (?:(?<=USD )|(?<=US\$))\d+, also returned ['120', '45'].
Cause 2: a quantifier such as \s* is inside
This is the spot where you want \s* because you do not know how many spaces there will be. With a log line price: 300 qty:2 price:45, (?<=price:\s*)\d+ was rejected with the same error, because the length is not fixed. When there is no upper bound on the number of spaces, this is a spot that per-branch lookbehinds cannot solve.
The fix: consume the prefix and pull out only the value in a group
A lookbehind is used to keep the prefix out of the result. You get the same effect by consuming the prefix with an ordinary pattern and then pulling out only the value with parentheses. An ordinary pattern has no restriction when the lengths differ or a quantifier is present.
re.findall(r"(?:USD |US\$)(\d+)", text) # ['120', '45']
re.findall(r"price:\s*(\d+)", log) # ['300', '45']
There are two rules. Wrap the prefix in (?:...) so it is not counted as a group, and put the value you want in exactly one pair of parentheses. That is because re.findall returns the list of that group’s strings when there is one group. Without the parentheses you get the whole match, prefix included. Conversely, with two or more pairs of parentheses you get a list of tuples.
re.findall(r"(?:USD |US\$)\d+", text) # ['USD 120', 'US$45'] <- not just the value
re.findall(r"(USD |US\$)(\d+)", text) # [('USD ', '120'), ('US$', '45')]
In re.sub, which replaces strings, bring the prefix back with group numbers so it is not erased.
re.sub(r"(USD |US\$)(\d+)", r"\g<1>[\2]", text)
# '주문 USD [120], 환불 US$[45], 배송 EUR 7'
Rewriting three common shapes
Here are three common patterns that the same approach handles. Each input is a single line, and the results below were the same on all three Pythons. The first two rows are the same branch-length problem as cause 1, and the third is a problem where ? leaves the length undetermined.
| Before (error) | After | Input | Result after |
|---|---|---|---|
(?<=id=|uid=)\d+ |
(?:id=|uid=)(\d+) |
id=7 uid=42 |
['7', '42'] |
(?<=^|,)\w+ |
(?:^|,)(\w+) |
a,b,c |
['a', 'b', 'c'] |
(?<=https?://)[\w.]+ |
https?://([\w.]+) |
http://a.com https://b.com |
['a.com', 'b.com'] |
In the second row, ^ has length 0 and , has length 1, so the branch lengths differ. It is a shape that comes up often when one pattern has to catch both the first value and the values after commas.
When the prefix overlaps the previous match
Consuming is not exactly the same as a lookbehind. On 1,2,3, using “digit then comma” as the condition before a number, the lookbehind (?<=\d,)\d+ returned ['2', '3'], but the consuming \d,(\d+) returned only ['2']. This article’s interpretation is that 1,2 is read in one go, so the 2 before the 3 has already been used. If the prefix has branches of different lengths and the input can overlap with the previous match, put each branch in its own lookbehind. On 1,2, 3, (?:(?<=\d,)|(?<=\d, ))\d+ returned ['2', '3'], while the consuming \d,\s*(\d+) returned only ['2'].
Where overlap and \s* are both needed, the standard re lookbehind ((?<=\d,\s*)\d+) is rejected with the same error. In that spot the regex module in the next section returned ['2', '3'].
Another route: the regex module and Node
After installing the third-party regex module (2026.11.19) with pip, the original pattern (?<=USD |US\$)\d+ returned ['120', '45'] as is, and (?<=\d,\s*)\d+ passed too. If your script uses only the standard library, the fix above adds no dependency. The same pattern also returned ['120', '45'] in Node v26.7.0’s regular expressions (other languages were not tested) with no error.
Test scope and limits
Tests ran on macOS 26.6.2 arm64 with the system Python 3.9.6 and Homebrew Python 3.12.13 and 3.14.7, and running the whole test twice gave the same output. For | branches of different lengths, \s* and the negative form (?<!...), the error message was confirmed; for | branches of the same length, the passing result was confirmed. Python 3.13 itself was not installed, and the PatternError name was confirmed only on 3.14 and in the official documentation. The overlap cases used only the two inputs 1,2,3 and 1,2, 3. For the negative form only the same error was confirmed and no fix is covered. Windows, Linux, PyPy, speed on large inputs, and other versions of the regex module were not tested. The three rows of the table were each tried on a single input line. The sample strings are single lines made by hand, so real log files and inputs with other character makeups were not tried.
Three-line summary
- Python re’s lookbehind needs one fixed length inside, so
|branches of different lengths and\s*are rejected withlook-behind requires fixed-width pattern. - Remove the lookbehind, consume the prefix with
(?:...), and pull out only the value with one(...); on inputs where the prefix does not overlap the previous match, the same values come out. - The third-party
regexmodule passed the original pattern as is, but if you use only the standard library, the capture-group fix is enough.