basu76
basu76

Reputation: 481

Regular Expression to Match character at a position and ignore characters after

Want to match the character at position 7 to either be - or an Uppercase letter

This is what I have ^.{6}[-(A-Z)]

Though this matches the first 7 characters, it doesn't match the whole string. Any help appreciated.

I am using Java and wanting .matches() to return true for this String

Upvotes: 0

Views: 2552

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Though this matches the first 7 characters, it doesn't match the whole string.

That's the right explanation of what is going on. You can skip over the rest of the string by adding .* at the end. Additionally, the ^ anchor at the front of the expression is implied, so you can drop it for a pattern of

.{6}[A-Z-].*

Upvotes: 1

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

As mentioned You can use .* to match anything after your specific character so use

^.{6}[-A-Z].*

and also no need of () if you don't want to capture that specific character

Upvotes: 1

Related Questions