I am trying to find all occurrences of the following regex \%\%comp\.[^%]+\%\% and replace them with \%comp\.[^%]+\% (i.e reducing one % from both ends).
What is the easiest way to do this in go, aside from using findallindex matches and cleaning up the string in reverse order?
You can use Regexp.ReplaceAll method for that. Example:
re := regexp.MustCompile(`\%(\%comp\.([^%]+)\%)\%`)
fmt.Printf("%s\n", re.ReplaceAll([]byte("test%%comp.test%%"), []byte("$1")))
>>> OUTPUT: test%comp.test%
Notice, that $n is used in replacement string to expand value from nth group in regexp.
Related
I have strings like
#(foo) 5 + foo.^2
#(bar) bar(1,:) + bar(4,:)
and want the expression in the first group of parentheses (which could be anything) to be replaced by x in the whole string
#(x) 5 + x.^2
#(x) x(1,:) + x(4,:)
I thought this would be possible with regexprep in one step somehow, but after reading the docu and fiddling around for quite a while, I have not found a working solution, yet.
I know, one could use two commands: First, grab the string to be matched with regexp and then use it with regexprep to replace all occurrences.
However, I have the gut feeling this should be somehow possible with the functionality of dynamic expressions and tokens or the like.
Without the support of an infinite-width lookbehind, you cannot do that in one step with a single call to regexprep.
Use the first idea: extract the first word and then replace it with x when found in between word boundaries:
s = '#(bar) bar(1,:) + bar(4,:)';
word = regexp(s, '^#\((\w+)\)','tokens'){1}{1};
s = regexprep(s, strcat('\<',word,'\>'), 'x');
Output: #(x) x(1,:) + x(4,:)
The ^#\((\w+)\) regex matches the #( at the start of the string, then captures alphanumeric or _ chars into Group 1 and then matches a ). tokens option allows accessing the captured substring, and then the strcat('\<',word,'\>') part builds the whole word matching regex for the regexprep command.
How can I extract a substring from within a string in Ruby?
Example:
String1 = "<name> <substring>"
I want to extract substring from String1 (i.e. everything within the last occurrence of < and >).
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] → new_str or nil
String1.scan(/<([^>]*)>/).last.first
scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.
You can use a regular expression for that pretty easily…
Allowing spaces around the word (but not keeping them):
str.match(/< ?([^>]+) ?>\Z/)[1]
Or without the spaces allowed:
str.match(/<([^>]+)>\Z/)[1]
Here's a slightly more flexible approach using the match method. With this, you can extract more than one string:
s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)
# Use 'captures' to get an array of the captures
matchdata.captures # ["ants","pants"]
# Or use raw indices
matchdata[0] # whole regex match: "<ants> <pants>"
matchdata[1] # first capture: "ants"
matchdata[2] # second capture: "pants"
A simpler scan would be:
String1.scan(/<(\S+)>/).last
I've searched for this answer but haven't found an answer that exactly works.
I have the following pattern where the hashes are any digit: 102###-###:#####-### or 102###-###:#####-####
It must start with 102 and the last set in the pattern can either be 3 or 4 digits.
The problem is that I can have a string with between 1-5 of these patterns in it with any sort of characters in between (spaces, letters etc). The Regex I posted below matches the patterns well but I am trying to select everything that is NOT this pattern so I can remove it. The end goal is to extract all the patterns and just have all the patterns comma delimited as the output. (Pattern, Pattern, Pattern) How do I accomplish this with regex?Perhaps there is a better way than trying to take this line? Thanks. This is using VBA.
Regex For Pattern:(\D102\d{3}-\d{3}:\d{5}-\d{3,4}\D)
String Example: type:102456-345:56746-234 102456-345:56746-2343 FollowingCell#:102456-345:56746-234 exampletext##$% 102456-345:56746-2345 stuff
No need to grab everything you don't need to remove it: That's more difficult. Just grab everything you need and do whatever you want with it.
See regex in use here
(?<!\d)102\d{3}-\d{3}:\d{5}-\d{3,4}(?!\d)
See code in use here
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim sourcestring as String = "type:102456-345:56746-234 102456-345:56746-2343 FollowingCell#:102456-345:56746-234 exampletext##$% 102456-345:56746-2345 stuff"
Dim re As Regex = New Regex("(?<!\d)102\d{3}-\d{3}:\d{5}-\d{3,4}(?!\d)")
Dim mc as MatchCollection = re.Matches(sourcestring)
For each m as Match in mc
Console.WriteLine(m.Groups(0).Value)
Next
End Sub
End Module
Result:
102456-345:56746-234
102456-345:56746-2343
102456-345:56746-234
102456-345:56746-2345
I am trying to select everything that is NOT this pattern so I can remove it. The end goal is to extract all the patterns and just have all the patterns comma delimited as the output
If you want to extract the patterns, then just do that, without removing everything around them. Example in Python: (Posted before the question's language was specified, but I'm sure the same can be done in VBA.)
>>> import re
>>> p = r"102\d{3}-\d{3}:\d{5}-\d{3,4}"
>>> text = "type:102456-345:56746-234 102456-345:56746-2343 FollowingCell#:102456-345:56746-234 exampletext##$% 102456-345:56746-2345 stuff"
>>> ",".join(re.findall(p, text))
'102456-345:56746-234,102456-345:56746-2343,102456-345:56746-234,102456-345:56746-2345'
I have a series of strings which are identifiable by finding a substring "p" tag followed by at least two CAPITAL letters.
Input:
<p>JIM <p>SALLY <p>ROBERT <p>Eric
I want to change the "p" tag to an "i" tag if it's followed by those two capital letters (so not the last one, 'Eric').
Desired output:
<i>JIM <i>SALLY <i>ROBERT <p>Eric
I've tried this using regular expressions in Python:
import re
Mytext = "<p>JIM <p>SALLY <p>ROBERT <p>Eric"
changeTags = re.sub('<p>[A-Z]{2}', '<i>' + re.search('<p>[A-Z]{2}', Mytext).group()[-2:], Mytext)
print changeTags
But the output uses "i" tag + JI in every instance, rather than interating through to use SA and then RO in entries 2 and 3.
<i>JIM <i>JILLY <i>JIBERT <p>Eric
I believe the problem is that I don't understand the .group() method properly. Can anyone advise what I've done wrong?
Thank you.
Another way using look-ahead assertion:
re.sub(r'<p>(?=[A-Z]{2,})','<i>',MyText)
Your inner re.search is only evaluted once, and the result is passed as one of the parameters to re.sub. This can't possible capture all the capital-letters-pairs, only the first one. This means your approach cannot work, not merely your understanding of groups.
Furthermore, using groups is unnecessary.
You need to capture the capital letters using parenthesis, and reference it as \1 in the substitution expression:
re.sub('<p>([A-Z]{2})', r'<i>\1', Mytext)
\1 here means: replace with the substring matched by the first (...) in the regular expression. (docs)
Note the leading r in front of the substitution string, to make it raw.
i have following statement {$("#aprilfoolc").val("HoliWed27"); $("#UgadHieXampp").val("ugadicome");}.and i want to get the string with combination.i have written following regex but it is not working.
please help!
(?=[\$("#]?)[\w]*(?<=[")]?)
Your lookaround assertions are using character classes by mistake, and you've confused lookbehind and lookahead. Try the following:
(?<=\$\(")\w*(?="\))
You could use this simpler one :
'{$("#aprilfoolc").val("HoliWed27");}'.match(/\$\(\"#(\w+)\"[^"]*"(\w+)"/)
This returns
["$("#aprilfoolc").val("HoliWed27"", "aprilfoolc", "HoliWed27"]
where the strings you want are at indexes 1 and 2.
This construction
(?=[\$*"#]?)
will match a lookahead, but only optional -- the character set is followed by a ?. This kind of defeats the next part,
[\w]
which matches word characters only. So the lookahead will never match. Similar, this part
(?<=[")])
will also never match, because logically there can never be one of the characters " or ) at the end of a string that matches \w only. Again, since this portion is optional (that ? at the end again) it will simply never match.
It's a bit unclear what you are after. Strings inside double quotes, yes, but in the first one you want to skip the hash -- why? Given your input and desired output, this ought to work:
\w+(?=")
Also possible:
/\("[#]?(.*?)"\)/
import re
s='{$("#aprilfoolc").val("HoliWed27");}'
f = re.findall(r'\("[#]?(.*?)"\)',s)
for m in f:
print m
I don't know why, but if you want capturing of two groups simultaneously, so:
/\("#(.*?)"\).*?\("(.*?)"\)/
import re
s='{$("#aprilfoolc").val("HoliWed27");}'
f = re.findall(r'\("#(.*?)"\).*?\("(.*?)"\)',s)
for m in f:
print m[0],m[1]
In JavaScript:
var s='{$("#aprilfoolc").val("HoliWed27")';
var re=/\("#(.*?)"\).*?\("(.*?)"\)/;
alert(s.match(re));