-1

I need a regular expression that finds T1 in a string. I don't want it to match however if there is any text in front of it (spaces are ok), so:

this is T1 - match

this isT1 - not a match

T1 - match

^(?=.*[T])(?=.*[0-4]) this is what i have currently that can match T1 up to T4.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user987723
  • 945
  • 3
  • 12
  • 33

1 Answers1

2

Checking for start or string or space before T1 will do.

Regex: (?<=^|\s)T\d+

Explanation: This looks-behind if there is any space before T1 or it is at beginning of string. If yes then T1, T2 or even T987 will match.

Regex101 Demo


Additionally

If you want to impose this restriction on both sides use following regex.

Regex: (?<=^|\s)T\d+(?=\s|$)

Explanation: This will lookahead as well as look-behind. Both on left and right side.

Regex101 Demo

  • @h2ooooooo: Done ! Also check [this answer for word boundary conflicts.](http://stackoverflow.com/questions/36617788/how-do-i-write-a-regex-to-match-all-single-characters-in-a-string/36617842#36617842) –  Apr 14 '16 at 12:52
  • And if the language flavor is JS? – Wiktor Stribiżew Apr 14 '16 at 12:54
  • @WiktorStribiżew: [NSRegularExpressions](http://stackoverflow.com/questions/24860703/regex-for-text-within-braces) support lookarounds, so we can use this. –  Apr 14 '16 at 12:59
  • 1
    The problem is, there are two tags, one for Qt and another one for Objective-C. Both are mostly used because there is "regular expression" inside these tags. However, it seems OP really might be coding for iOS (I checked OP history). – Wiktor Stribiżew Apr 14 '16 at 13:03
  • @WiktorStribiżew: Should wait for OP's reply to your comment. –  Apr 14 '16 at 13:04
  • **[QRegularExpression implements Perl-compatible regular expressions.](http://doc.qt.io/qt-5/qregularexpression.html#details)** I hope this means **Yes, it supports lookaround assertions.** –  Apr 14 '16 at 13:07
  • You misunderstood me: I mean the regex flavor may be any when those 2 tags are used alongside with the regex tag. – Wiktor Stribiżew Apr 14 '16 at 13:34
  • @noob: Wiktor is right, those two tags are used incorrectly more often than not, which is why I deleted them. Many, um, newcomers aren't confident that [tag:regex] is sufficient because it doesn't contain the whole phrase "regular expression". If they don't give some other indication that they're using iOS or qt or whatever, you should always question those tags. – Alan Moore Apr 16 '16 at 17:57