0

I have these inputs:

DFDBDFDFDF21R123
DFDBDFDFDF34R123

I want to match these inputs, except positions 9 and 10, like below:

DFDBDFDFxxR123
DFDBDFDFxxR123

So, to be clear: match 1-8, exclude 9-10, match 11-16.

Alan Moore
  • 68,531
  • 11
  • 88
  • 149
Espy
  • 19
  • 1
  • 1
    Possible duplicate of [How to match "any character" in Java Regular Expression?](http://stackoverflow.com/questions/2912894/how-to-match-any-character-in-java-regular-expression) – DavidS Mar 01 '16 at 21:16
  • Why not `(.{8})..(.+) `? –  Mar 01 '16 at 21:18
  • Or, `string_new = string_old.replace("(.{8})..(.+)", "$1$2");` –  Mar 01 '16 at 21:25

1 Answers1

1

To expand upon the answer from https://stackoverflow.com/users/557597/sln of

(.{8})..(.+)

The 'thing' you are missing from your understanding of Regex is 'grouping'

(SOME MATCHING SUB-STRING A)(SOME MATCHING SUB-STRING B)

If you use regex like this, you can do lots of nice things including 'pull out' parts of a line and then re-arrange them. But it also helps you group 'parts' that you want to search for.

so his

.{8}

matches '.' which is 'any single character' and then {8} means 'match any single character 8 times.

 (.{8})

means 'group the first 8 characters' for use.

..

means 'match any two characters'

 .+ 

means 'match 1 or more of 'any character'

 (.+)

means "group that 1 or more of 'any character' for later use"

Therefore...

When you put them all together you get

 (.{8})..(.+)

Which means 'match the first 8 characters (any 8 characters) as group 1' then 'any two characters' then '1 or more characters as group 2'

This would allow you to (depending on your regex client/etc.) is use $1 and $2 to print out, use or ...whatever... the values of group 1 and/or group 2.

Hope this helps.

mawalker
  • 2,077
  • 2
  • 17
  • 30
  • I don't see what grouping has to do with the user's question. He's looking to match some string while ignoring some characters. This can be achieved with `.`. There is no need to involve any other regex feature. – DavidS Mar 01 '16 at 23:53
  • ahh, he edited the question and made it more clear that he wanted 'exact' string matches, not 'whatever string matches this pattern' Then yes, this is a little bit much, and not actually 'exactly' what he needs, but still use of groups when does smart (even if you don't use them later) can help with regex clarity. – mawalker Mar 01 '16 at 23:56