Zaje
Zaje

Reputation: 2309

Regex to match not start of line

I have the following XML tag

<list message="2 < 3">

I want to replace the < in the text with &lt;

Need a regex to match < if it doesn't appear at the start of line.

Upvotes: 17

Views: 26577

Answers (6)

Connor
Connor

Reputation: 1

@duncan's method works fine if you just want to replacing, but it doesn't match the <. and all the lookbehind wont work if you a using javascript. because javascript doesn't support lookbehind, unless you turn on the --harmony flag in nodejs or experimental javascript features in chrome. But lookahead will work here, which is: /(?!^)</ will match the < which is not at the begining of a line. and the replacing will be: '<list message="2 < 3">'.replace(/(?!^)</, '&lt;')

Upvotes: 0

duncan
duncan

Reputation: 31912

[^<]+ = one or more characters that are not <

< = the < you're looking for

replace:

([^<]+)<

with:

$1&lt;

Upvotes: 8

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

This would give you "<" after the first instance:

[^<]<

Upvotes: 1

morphles
morphles

Reputation: 2503

Most likely you can do this using lookbehind:

/(?<!^)</

see: http://www.regular-expressions.info/lookaround.html

Upvotes: 35

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Try this:

(?<="[^"]*)<(?=[^"]*")

Upvotes: 0

SJuan76
SJuan76

Reputation: 24780

The dot '.' means "any value"

.<

Anyway, I suppose you don't want whitespaces, either. If so, then

\S\s*<

Upvotes: 5

Related Questions