J-H
J-H

Reputation: 1869

Regex to check preceding and following characters

i'm struggling to build a working regex to filter all hyphens "-" if and only if the preceding and following characters of the word are [a-zA-Z] without a digit or another hyphen sign.

For example i want to filter the hyphen of this word: Te-st but not for this T3E-st

My current approach is not working yet:

([a-zA-Z]+(-)+[\w]+)

Upvotes: 1

Views: 156

Answers (1)

anubhava
anubhava

Reputation: 785701

You can use lookarounds:

(?<=[a-zA-Z])-(?=[a-zA-Z])

This means match - if it is preceded and followed by an ASCII letter.

Update:

Java doesn't support infinite length lookbehind like .NET you can use something like:

(?<=^[a-zA-Z]{1,999})-(?=[a-zA-Z]*$)

Which will match - in Te-st but not in T3E-st

Upvotes: 3

Related Questions