Jeroen
Jeroen

Reputation: 1755

Looking for specific regex

I've been looking to create a regex for my specific situation. The furthest i've come with my own limited knowledge of Regex and by searching on StackOverflow is this Regex:

^[pP][a-zA-Z0-9- ]*

I'm looking for a Regex which forces the string to:

Examples of strings that should match the Regex:

What is the Regex I'm looking for? The language I'm using is C#

Upvotes: 5

Views: 903

Answers (3)

Francesco B.
Francesco B.

Reputation: 3107

Adding to @Zenoo's answer, if you want to take into account %20 as a single occurrence, you can use the following expression:

[pP]([a-zA-Z0-9 +-]|(%20)){14,}0000

where you basically add to the possible character list %20 as a single occurrence.

Here is the live demo, which you can use to test all the examples you want (I already included those you provided), with all the technical explanations needed, which I am copying below:

  • pP matches a single character in the list pP (case sensitive)
  • 1st Capturing Group ([a-zA-Z0-9 +-]|(%20)){14,} {14,} Quantifier — Matches between 13 and unlimited times, as many times as possible, giving back as needed (greedy)
  • 1st Alternative [a-zA-Z0-9 +-] Match a single character present in the list below [a-zA-Z0-9 +-] a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
  • A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive) 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
  • +- matches a single character in the list +- (case sensitive)
  • 2nd Alternative (%20) 2nd Capturing Group (%20) %20 matches the characters %20 literally (case sensitive)
  • 0000 matches the characters 0000 literally (case sensitive)

Upvotes: 4

revo
revo

Reputation: 48761

A regex can be used to precisely match the format:

^(?=.{14,}0000$)[pP][a-zA-Z0-9]*(?:(?(1)\1|([- +]|%20)?)[a-zA-Z0-9]+)*$
  • (?=.{14,}0000$) asserts a line which is >= 18 in length and ends with 0000
  • (?(1)\1|([- +]|%20)?) is an if clause which checks if delimiter is matched it should be used as the next delimiter

Live demo

Upvotes: 2

Zenoo
Zenoo

Reputation: 12880

You could try this RegEx : [pP][a-zA-Z0-9- +%]{13,}0000

[pP] matches a single character in the list pP (case sensitive)

{13,} matches 13 or more iterations of [a-zA-Z0-9- +%]

  • a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
  • A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
  • 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
  • - +% matches a single character in the list - +% (case sensitive)

0000 matches the characters 0000 literally (case sensitive)

Upvotes: 3

Related Questions