tombazza
tombazza

Reputation: 656

Need a regular expression to match letter followed by number or capital

I need a regular expression that can replace the lowercase letter n with a newline, but only when it is followed by a digit 0-9 or a capital letter.

For example, the string:
Company Buildingn100 Prospect Way

Should convert into:
Company Building
100 Prospect Way

I'm trying to sanitize this data in PHP, so the resulting expression needs to be compatible.

Upvotes: 3

Views: 1079

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

$result = preg_replace("/n(?=[\dA-Z])/", "\n", $subject);

will do this if by capital letter you mean ASCII letters.

$result = preg_replace("/n(?=[\d\p{Lu}])/u", "\n", $subject);

if you're using Unicode.

Upvotes: 3

Kobi
Kobi

Reputation: 138007

Try this:

n(?=[\dA-Z])

In PHP (working example):

$str = preg_replace("/n(?=[\dA-Z])/", "\n", $str);

(?=...) is a positive lookahead - it checks what's after the n we matched, but doesn't match it, so the next character isn't replaced.

Upvotes: 4

Related Questions