---
# System prepended metadata

title: 408. Valid Word Abbreviation

---

# 408. Valid Word Abbreviation

![](https://hackmd.io/_uploads/BkyByl4uc.png)

![](https://hackmd.io/_uploads/rJxDkx4u9.png)

```python=
class Solution:
    def validWordAbbreviation(self, word: str, abbr: str) -> bool:
        
        def is_legal(digit_st):
            return digit_st[0] != '0'

        digit_st = []
        j = -1  # ptr for `word`
        for i,x in enumerate(abbr):
            if x.isalpha():
                if digit_st != []:
                    if not is_legal(digit_st):
                        return False
                    j += int(''.join(digit_st)) + 1
                    digit_st.clear()
                else:
                    j += 1
                if j > len(word) - 1 or word[j] != x:
                    return False
            else:
                digit_st.append(x)
                
        if digit_st != []:
            if not is_legal(digit_st):
                return False
            j += int(''.join(digit_st))

        return j == len(word) - 1
    
```
## regex like a pro
https://leetcode.com/problems/valid-word-abbreviation/discuss/89541/Simple-Regex-One-liner-(Java-Python)
Use re.sub() to cast `abbr` into a regex 
and then use that regex to match `word`.
```python=
class Solution:
    def validWordAbbreviation(self, word: str, abbr: str) -> bool:    
        re_sub = re.sub('([1-9]\d*)', r'.{\1}', abbr)
        return bool(
            re.match(re_sub + '$', word)
        )
```


### regex
![](https://hackmd.io/_uploads/BkHlxgVdq.png)
### re.sub()
`/1` is the matched group
![](https://hackmd.io/_uploads/B1w_fgV_5.png)
https://docs.python.org/3/library/re.html
![](https://hackmd.io/_uploads/BkG-QeVOc.png)
