Regex position string - regex

For example i have this string.
$string = 'test***bas';
How can I display text before the stars with Regex?

You could use a regular expression which makes use of Capture Groups. Once that you have matched your input, you could then access the captured group and print the output.

The following pattern
^(.+?)\*\*\*
will create a group match using the parenthesis operators. See http://gskinner.com/RegExr/ for testing your regular expressions (there are many ways of testing online)
The language you use around your regular expression will have different ways of capturing groups so you will need to better explain what language you are using for any further advice.
Example for before and after asterix
^(.+?)\*\*\*(.+)$

If tou also want what is located after the ***, you can use the following:
$string = 'test***bas';
$pattern = '/(.+)\*{3}(.+)/';
preg_match($pattern, $string, $matches);
$matches will contain the results:
$matches[1] will be "test"
$matches[2] will be "bas"

Related

Can Regular Expression Capture Groups Be Modular or Variable?

Can a regular expression capture group be made variable?
Can regex captures be made modular so that they can be reused throughout a more complete regex?
Can you simplify a regex that has many captures of the same format?
There are some tricks you can use to make it modular.
You can make reusable patterns with qr//. This operator compiles a regular expression and returns it such that it can be saved to a variable. Capturing parenthesis are no different than any other regex term.
Those regex variables can be placed into larger regexes as if you had typed them out fully. A variable can also be plain text which will be compiled into the regex when it is run. This allows you to use the same code for several matching tasks. It makes your logic flow simpler and easier to understand and debug.
$string = "AM[740];FM[89.5];SW[200]";
$bracket_contents = qr/\[([^\]]*)\]/;
$thing = "AM";
$am_value = $string =~ m/\b$thing$bracket_contents/ ? $1 : undef;
$thing = "SW";
($sw_value) = $string =~ m/\b$thing$bracket_contents/;

How to filter unwanted parts of a PowerShell string with Regex and replace?

I am confused about the workings of PowerShell's -replace operator in regards to its use with regex. I've looked for documentation online but can't find any that goes into more detail than basic use: it looks for a string, and replaces that string with either another string (if defined) or nothing. Great.
I want to do the same thing as the person in this question where the user wants to extract a simple program name from a complex string. Here is the code that I am trying to replicate:
$string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
$program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
$program
SUB RAD MSD 50R III
As you can see the output string is the string that the user wants, and everything else is filtered out. The only difference for me is that I want a string that is composed of six digits and nothing else. However when I attempt to do it on a string with my regex, I get this:
$string2 = '1_123456_1'
$program2 = $string -replace '(\d{6})','$1'
$program2
1_123456_1
There is no change. Why is this happening? What should my code be instead? Furthermore, what is the $1 used for in the code?
The -replace operator only replaces the part of the string that matches. A capture group matches some subset of the match (or all of it), and the capture group can be referenced in the replace string as you've seen.
Your second example only ever matches that part you want to extract. So you need to ensure that you match the whole string but only capture the part you want to keep, then make the replacement string match your capture:
$string2 = '1_123456_1'
$program2 = $string -replace '\d_(\d{6})_\d','$1'
$program2
How you match "the rest of the string" is up to you; it depends on what could be contained in it. So what I did above is just one possible way. Other possible patterns:
1_(\d{6})_1
[^_]*_(\d{6})_[^_]*
^.*?(\d{6}).*?$
Capturing groups (pairs of unescaped parentheses) in the pattern are used to allow easy access to parts of a match. When you use -replace on a string, all non-overlapping substrings are matched, and these substrings are replaced/removed.
In your case, -replace '(\d{6})', '$1' means you replace the whole match (that is equal to the first capture, since you enclosed the whole pattern with a capturing group) with itself.
Use -match in cases like yours when you want to get a part of the string:
PS> $string2 = '1_123456_1'
PS> $string2 -match '[0-9]{6}'
PS> $Matches[0]
123456
The -match will get you the first match, just what you want.
Use -replace when you need to get a modified string back (reformatting a string, inserting/removing chars and suchlike).

Capturing some different part of text and replacing with another

There is a deprecated function in PHP and for that reason, I need to replace all functions with their replacements. Since some of the arguments have different values, I need to use a regex find-and-replace method to do this.
For example I have two functions:
mysql_result($one,0,"val1")
mysql_result($two,0,"val2")
How can I write a regex to convert this two into those?
$one["val1"]
$two["val2"]
Currently I have (mysql_result\()*\"\) but this only matches the ending part of the function.
You can use this pattern, then substitute with $1["$2"]:
.*?\(([^,]+).*?"([^"]+).*
Live DEMO
Edit:
$string = array('mysql_result($one,0,"val1")', 'mysql_result($two,0,"val2")');
$pattern = '/.*?\(([^,]+).*?"([^"]+).*/';
print_r( preg_replace($pattern, '$1["$2"]', $string ));
Working DEMO
preg_replace('/mysql_result\(([^,]*),[^,]*,([^)]*)\)/', '$1[$2]', $string);
Use following regexRegEx: (mysql_result\()(.*),(.*),(.*)(\))
And replace it with following: \2[\4]

Regular expression using powershell

Here's is the scenario, i have these lines mentioned below i wanted to extract only the middle character in between two dots.
"scvmm.new.resources" --> This after an regular expression match should return only "new"
"sc.new1.rerces" --> This after an regular expression match should return only "new1"
What my basic requirement was to exract anything between two dots anything can come in prefix and suffix
(.*).<required code>.(.*)
Could anyone please help me out??
You can do that without using regex. Split the string on '.' and grab the middle element:
PS> "scvmm.new.resources".Split('.')[1]
new
Or this
'scvmm.new.resources' -replace '.*\.(.*)\..*', '$1'
Like this:
([regex]::Match("scvmm.new1.resources", '(?<=\.)([^\.]*)(?=\.)' )).value
You don't actually need regular expressions for such a trivial substring extraction. Like Shay's Split('.') one can use IndexOf() for similar effect like so,
$s = "scvmm.new.resources"
$l = $s.IndexOf(".")+1
$r = $s.IndexOf(".", $l)
$s.Substring($l, $r-$l) # Prints new
$s = "sc.new1.rerces"
$l = $s.IndexOf(".")+1
$r = $s.IndexOf(".", $l)
$s.Substring($l, $r-$l) # Prints new1
This looks the first occurence of a dot. Then it looks for first occurense of a dot after the first hit. Then it extracts the characters between the two locations. This is useful in, say, scenarios in which the separation characters are not the same (though the Split() way would work in many cases too).

Using regular expression to extract full words from text

I have been working with parsing data, I got a string like:
"Scottish Premier League (click here to open|close this coupon)"
I would like to extract "Scottish Premier League" with Scottish Matching Group 1 and Premier League Matching Group 2, using regular expression.
Please show me the way to do that using regular expression.
MatchCollection matchCol = reg.Matches("Scottish Premier League (click here to open|close this coupon)");
If you just want to match each specific word then your regex could be something like:
(Scottish) (Premier League)
If you want to match the first word then the next two:
([\w]+) ([\w]+ [\w]+)
Another way of writing this that accounts for multiple spaces between words is:
(\w+)\s+(\w+\s+\w+)
/(Scottish) (Premier League)/
Basic and direct:
$s = "Scottish Premier League (click ... coupon)";
$s =~ m/(Scottish) (Premier League)/;
print "Match groups one and two: '$1' '$2'\n";
You probably wanted more generalized matching:
$s = "Generalized Matching on a string (click ... coupon)";
$s =~ m/^(\S+)\s(.+)\s+\(click/;
print "Match groups one and two: '$1' '$2'\n";
These are Perl; be more specific next time.
Also, help yourself, use a tool, like RegexBuddy or Expresso.
Given that you only gave one string to which the regex would be applied, it is hard to tell if this solution would work for your various other cases:
/^(\w*) (.*) \(/