Usman Mutawakil
Usman Mutawakil

Reputation: 5259

Regular Expressions: Reducing duplication

Is there a way to simplify an expression such as this

([0-9]||[A-Z])([0-9]||[A-Z])([0-9]||[A-Z])([0-9]||[A-Z])([0-9]||[A-Z])([0-9]||[A-Z])

to something like {([0-9]||[A-Z]) = B } BBBBBB Where B represents a duplication of a sub expression.

I'm coding in labVIEW but I'm interested in a solution that is language independent.

Upvotes: 3

Views: 704

Answers (3)

Anirudha
Anirudha

Reputation: 32807

You can specify the number of times a particular regex pattern would repeat using .,*,+,? or {} quantifiers

.->match only 1 time
*->0 to many times
+->1 to many times
?->0 or 1 time
{}->Exact matches..For example:{1}->1 times {1,8}->1 to 8 times

In your case it should be

([0-9]||[A-Z]){6}

NOTE (In case you want EXACT duplicates)

if you want to capture the same pattern..then you would have to use the reference to the previously captured group

So,

with the below regex

(hello) \1

you can match hello hello

So,in your case if you want the exact duplicate to repeat 6 times,you can do this

([0-9]||[A-Z])\1{5}

Upvotes: 2

Nick
Nick

Reputation: 4362

Try this: ([0-9]||[A-Z]){6}

You can use {x} to designate the number of times you want it to show up. {6} means the pattern 6 times. You can use {1,6} to mean 1, 2, 3, 4, 5, 6 times.

One thing I like to have printed up next to my desk if I'm using Regular Expressions is this:

Regular Expression Cheat Sheet

It has saved me a number of times on syntax and such.

Upvotes: 3

Benj
Benj

Reputation: 32398

Sure, you can just:

([0-9]||[A-Z]){6}

The 6 refers to the number of items you'll accept. You can also:

([0-9]||[A-Z]){3,6}

Which would mean accept between 3 and 6 of these...

Upvotes: 4

Related Questions