Use RegEx to search pattern, exclude another - regex

I'm using Regex to include all patterns except one.
My code so far:
for root, dirs, files, in os.walk('z:/rod/folder'):
for name in files:
currentfile=os.path.join(root,name)
with open(currentfile) as d:
text = d.read()
regex = re.compile('2\sFF\s{28}\d\sLOANS')
a = regex.findall(text)
if a:
with open('z:/rod/results.txt', 'a') as f:
f.write(os.path.join(root,name))
f.write('\n')
This code will include all files where '2 FF (any number) LOANS' which is OK, but I do not want any files that has a zero in the string - for example:
'2 FF 0 LOANS'
If the files has any other number in the string, such as, '2 FF 75 LOANS' - this is OK. But I do not want '2 FF 0 LOANS'.
Does this make sense? please help me finish the code.

You can try the following regex:
2\sFF\s(?!0 )\d+\sLOANS
\s(?!0 ) will only match the space if its not followed by a zero and a space. With this regex strings with multiple zeros will be matched. For example 2 FF 0000 LOANS will be matched.
If you do not want this you can use this:
2\sFF\s(?!0+ )\d+\sLOANS

Related

Vb.net regex finding a pattern after 5 spaces and 2 characters

I am trying to work on this regex pattern and match below examples. There are 5 spaces after Rx which I have tried to use " *", for but no luck.
("RX," *",\w\w(\w\w\w\w))
1) 18468.0 Rx 1CEBF900 8 02 00 00 80 00 01 01 FF - ' should match EBF9
2) 18468.6 Rx 18FD4000 8 FF FF 00 FF FF FF FF FF - 'should match FD40
ETC . . .
This expression seems to work:
Rx\s{5}\S{2}(.{4})
Function GetValue(line As String) As String
Dim regex As New Regex("Rx {5}\S{2}(.{4})")
Dim match As Match = regex.Match(line)
If match.Success Then Return match.Groups(1).Value
Return Nothing
End Function
See it here:
https://dotnetfiddle.net/yY3xXX
Here is a pattern that seems to extract the specific data you're seeking. It was generated and tested via RegExr.
Search Pattern: /(Rx {5}[0-9A-F]{2})([0-9A-F]{4})/g;
List/Replace Pattern: $2
Description: the first capture group specifies "Rx", five spaces, and two hexadecimal range characters; the second capture group specifies the next four hexadecimal range characters.
With your shown samples and attempts please try following regex and vb.net code. This will result EBF9 and FD40 values in output. Here is the Online demo for used regex in following.
Regex used for solution is:(?<=\s+Rx\s{5}.{2})\S+(?=\d{2}).
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim regex As Regex = New Regex("(?<=\s+Rx\s{5}.{2})\S+(?=\d{2})")
Dim match As Match = regex.Match("18468.0 Rx 1CEBF900 8 02 00 00 80 00 01 01 FF")
If match.Success Then
Console.WriteLine("RESULT: [{0}]", match)
End If
Dim match1 As Match = regex.Match("18468.6 Rx 18FD4000 8 FF FF 00 FF FF FF FF FF")
If match1.Success Then
Console.WriteLine("RESULT: [{0}]", match1.Value)
End If
End Sub
End Module
Explanation of regex:
(?<=\s+Rx\s{5}.{2}) ##Positive look behind to make sure Rx followed
##by 5 spaces followed by 2 any characters present.
\S+ ##matching all non-spaces here.
(?=\d{2}) ##Making sure they are followed by 2 digits.
Also I have taken both of your sample lines in 2 different variables just to show 2 lines output.

Extracting multi values with regex ( Only values, Not Fieldname )

Can someone help me with this regex?
I would like to extract either 1. or 2.
1.
(2624594000) 303 days, 18:32:20.00 <-- Timeticks
.1.3.6.1.4.1.14179.2.6.3.39. <-- OID
Hex-STRING: 54 4A 00 C8 73 70 <-- Hex-STRING (need "Hex-STRING" ifself too)
0 <--INTEGER
"NJTHAP027" <- STRING
OR
2.
Timeticks: (2624594000) 303 days, 18:32:20.00
OID: .1.3.6.1.4.1.14179.2.6.3.39
Hex-STRING: 54 4A 00 C8 73 70
INTEGER: 0
STRING: "NJTHAP027"
This filedname and value will return different data each time. (The data will be variable.)
I don't need to get the field names and only want to get the values in order from the top (multi value)
(?s)[^=]+\s=\s(?<value_v2c>([^=]+)-)
https://regex101.com/r/lsKeEM/2
-> I can't extract the last STRING: "NJTHAP027" at all!
The named group value_v2c is already a group, so you can omit the inner capture group.
Currently the - char should always be matched in the pattern, but you can either match it or assert the end of the string.
As you are using negated character classes and [^=]+ and \s, you can omit the inline modifier (?s) as both already match newlines.
To match the 2. variation, you can update the pattern to:
[^=]+\s=\s(?<value_v2c>[^=]+)(?:-|$)
Regex demo
To get the 1. version, you can match all before the colon as long as it is not Hex-String.
Then in the group optionally match it.
[^=]+\s=\s(?:(?!Hex-STRING:)[^:])*:?\s*(?<value_v2c>(?:Hex-STRING: )?[^=]+?)(?: -|$)
Regex demo

Regex pattern to match "AA BB CC DD"

I have a hexadecimal string with space separator for each byte.
eg., A1 B2 C3 D4 E5 FF 00 11 22 33 44 ...
I would like to use a regex validator to verify the user input is correct or not?
How could I write the regular expression to achieve this goal?
Something like this:
^[A-F0-9]{2}( [A-F0-9]{2})*$
Explanation:
^ - anchor: string start
[A-F0-9]{2} - two symbols in either 0..9 or A..F range
( [A-F0-9]{2})* - followed by space and two 0..9 or A..F symbols zero or more times
$ - anchor: string end
If you allow a..f as valid hexadecimal symbols
^[A-Fa-f0-9]{2}( [A-Fa-f0-9]{2})*$
I would like to propose a solution based on DRY principle
(Don't Repeat Yourself).
Instead of writing the same pattern (as Dmitry proposed), you can:
Write the pattern for 2 hex digits as a capturing group - ([A-F0-9]{2}).
"Call" it again using (?1).
So the whole pattern can be ^([A-F0-9]{2})( (?1))*$.
There are also other variants of "calling" a capturing group, e.g.
(?-1) - call the preceding group or
(?&name) - call a named group.
For details see https://www.regular-expressions.info/subroutine.html

Grouping lines with a header using regex

I'm trying to write a regex query that groups lines which start with a type of key as a header.
For example the key will be an line containing an 'A' followed by a number, I'm alternating bold lines to indicate a group. So the first 4 lines are one group, the next 2 a group etc. :
dd A3
This line is arbitrary
This line is also arbitrary
1234 Arbitrary
A9
This line is arbitrary
ff A3 d
A5ff
Hi there
Hello
This is what I ended up with that worked: .A[0-9].*\n((?!A[0-9]).|\n)

Find all substrings with at least one group

I try to find in a string all substring that meet the condition.
Let's say we've got string:
s = 'some text 1a 2a 3 xx sometext 1b yyy some text 2b.'
I need to apply search pattern {(one (group of words), two (another group of words), three (another group of words)), word}. First three positions are optional, but there should be at least one of them. If so, I need a word after them.
Output should be:
2a 1a 3 xx
1b yyy
2b
I wrote this expression:
find_it = re.compile(r"((?P<one>\b1a\s|\b1b\s)|" +
r"(?P<two>\b2a\s|\b2b\s)|" +
r"(?P<three>\b3\s|\b3b\s))+" +
r"(?P<word>\w+)?")
Every group contain set or different words (not 1a, 1b). And I can't mix them into one group. It should be None if group is empty. Obviously the result is wrong.
find_it.findall(s)
> 2a 1a 2a 3 xx
> 1b 1b yyy
I am grateful for your help!
You can use following regex :
>>> reg=re.compile('((?:(?:[12][ab]|3b?)\s?)+(?:\w+|\.))')
>>> reg.findall(s)
['1a 2a 3 xx', '1b yyy', '2b.']
Here I just concise your regex by using character class and modifier ?.The following regex is contain 2 part :
[12][ab]|3b?
[12][ab] will match 1a,1b,2a,2b and 3b? will match 3b and 3.
And if you don't want the dot at the end of 2b you can use following regex using a positive look ahead that is more general than preceding regex (because making \s optional is not a good idea in first group):
>>> reg=re.compile('((?:(?:[12][ab]|3b?)\s)+\w+|(?:(?:[12][ab]|3b?))+(?=\.|$))')
>>> reg.findall(s)
['1a 2a 3 xx', '1b yyy', '2b']
Also if your numbers and example substrings are just instances you can use [0-9][a-z] as a general regex :
>>> reg=re.compile('((?:[0-9][a-z]?\s)+\w+|(?:[0-9][a-z]?)+(?=\.|$))')
>>> reg.findall(s)
['1a 2a 3 xx', '1b yyy', '5h 9 7y examole', '2b']