user1711160
user1711160

Reputation: 169

Avoid matching escaped characters in regular exprssion

I want escape some characters in string and make regular expression to not match it.

Example in scala code:

val regexp = "<".r
val testedString = "< \\< <"
val resultList = regexp.findAllMatchIn(testedString).toList.map(m => m.start)
val wrongList = List(0, 3, 5)
val correctList = List(0, 5)

val isWrongList = resultList == wrongList
val isCorrectList = resultList == correctList

And it evaluates to:

regexp: scala.util.matching.Regex = <
testedString: String = < \< <
resultList: List[Int] = List(0, 3, 5)
wrongList: List[Int] = List(0, 3, 5)
correctList: List[Int] = List(0, 5)  

isWrongList: Boolean = true
isCorrectList: Boolean = false

What i want to do, is escape second '<' character and match only these on positon 0 and 5. So, the isCorrectList should evaluate to true and isWrongList should evaluate to false.

Can you help me write this regexp or give any clue?

Upvotes: 2

Views: 55

Answers (1)

anubhava
anubhava

Reputation: 786091

You can use a negative lookbehind in your regex:

val regexp = "(?<!\\\\)<".r

to prevent matching \< cases.

RegEx Demo

Upvotes: 2

Related Questions