1

I am trying to get a substring from a string using powershell. I want to get the string between "=%7B" and "%"

my string = "onething=%7BABCDEFGHIJKLM%something=%7BNOPQRSTUVWXYZ%"

I used the regex \=%7B([^%]+)\% and was able to get

"=%7BABCDEFGHIJKLM%" and "=%7BNOPQRSTUVWXYZ%"

but not the value that is inside the 2 strings. How is this done?

Thanks

wp78de
  • 18,207
  • 7
  • 43
  • 71
qwert
  • 301
  • 1
  • 2
  • 11

2 Answers2

3

Pretty easy with regex lookaround:

(?<=\=%7)[A-Z]+(?=%)

Try it on online.

If you use a more open pattern in the middle you should add an ungreedy flag:

(?<=\=%7).+?(?=%)

Use it like this:

$str="onething=%7BABCDEFGHIJKLM%something=%7BNOPQRSTUVWXYZ%"
$ret = [Regex]::Matches($str, "(?<=\=%7).+?(?=%)")
for($i = 0; $i -lt $ret.Count; $i++) {
    $ret[0].Value
}

You do not need to use a capturing group since my pattern gives a full match.


Explanation:

Positive Lookbehind (?<=%7) Assert that the Regex matches the characters %7 literally (case sensitive)

Match a single character present in the list below [A-Z]+
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
A-Z a single character in the range between A and Z (case sensitive)

Positive Lookahead (?=%)
Assert that the Regex below matches: matches the character % literally

Global pattern flags g modifier: global. All matches (don't return after first match)
U modifier: Ungreedy. The match becomes lazy by default. Now a ? following a quantifier makes it greedy

wp78de
  • 18,207
  • 7
  • 43
  • 71
  • Nice post ! I've been looking into regex lookaround the last few days. I can recommend the following source to get you started with Regex in general : https://github.com/zeeshanu/learn-REGEX – Snak3d0c Oct 03 '17 at 08:40
0

Looks like you are close...I am guessing based on what you posted since you did not post fully working code to reproduce the problem...

I ran this in ISE after verifying your regex at regex101.com.

$str="onething=%7BABCDEFGHIJKLM%something=%7BNOPQRSTUVWXYZ%"
$ret = [Regex]::Matches($str, "\=%7B([^%]+)\%")
$ret.Count
$ret[0].Groups[1].Value
$ret[1].Groups[1].Value

Worked for me...

Note, in the future, post code with proper syntax for improved responses to your questions...especially as they become more technical as your PowerShell problems will no doubt become.

Kory Gill
  • 6,993
  • 1
  • 25
  • 33