Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - regex to get "words" containing letters and (numbers/certain special), but not only numbers

In short: I'd like to match any "word" (contiguous set of characters separated by whitespace) containing 1 letter and at least 1 of (numbers/certain special characters). These "words" can appear anywhere in a sentence.

Trying this in python using re So far, as a pattern, I have:

w*[d@]w*

Which works, for the most part; however, I don't want to have "words" that are only numbers/special. Ex:

Should match:

h1DF346
123FE453
3f3g6hj7j5v3
hasdf@asdf
r3
r@

Should not match:

555555
@
hello
onlyletters

Having trouble excluding the first two under "should not match". Feel like there's something simple I'm missing here. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would use the | or operator like this:

([A-Za-z]+[d@]+[w@]*|[d@]+[A-Za-z]+[w@]*)

meaning you want:

  • letters followed by numbers@ followed by any combination,
  • or numbers@ followed by letters followed by any combination

Check the regex101 demo here

consider using non-capturing groups (?:...) instead of (...) if you are working with groups in other parts of your regular expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...