+ 2

Write a regular expression that matches a string that contains a character that is not a or b.

30th Apr 2018, 2:08 AM
chris
chris - avatar
10 Antworten
+ 4
also is this a good way to test it : import re if re.search("^[^ab]+
quot;, "hello word"): print("hello world")
30th Apr 2018, 6:59 AM
chris
chris - avatar
+ 4
It "[^ab]" will return the 1st char which is not a or b from the entire string "abstringab".match(/[^ab]/) //returns s And that must be one of the worst way to get interactive feedback. you do not see what was matched. if you insist then try the below code. it should be good enough. import re #re = 'abstring' regex = r"[^ab]" str = "abstring" match = (re.search(regex, str)) print(match)
30th Apr 2018, 10:57 AM
Lord Krishna
Lord Krishna - avatar
+ 4
lets say i want to write a regular expression that matches a string that contains a or b would it be "[ab]" or will this match the first charater?
30th Apr 2018, 4:44 PM
chris
chris - avatar
+ 3
That matches the 1st char found in a string. even if it contains ab. You asked for a regex which "matches a string that does not contain a or b." That fails for this string and returns the 1st matched char k "abkmnab" using "[^ab]" # returns k But using "^[^ab]+
quot; it matches the whole string from start to finish only if it does not contain a or b in it "abkmnab".match(/^[^ab]+$/) // string contains a; so no match "string".match(/^[^ab]+$/) //returns string
30th Apr 2018, 6:03 AM
Lord Krishna
Lord Krishna - avatar
+ 2
It's a trivial example all you need to do is match anything that is not a or b. A basic regex would be this "^[^ab]+
quot;. The "^" carat *inside* the square brackets means do not match strings which contain a or b. If you do not know regex basics check the below resources. https://www.regexone.com/references/JUMP_LINK__&&__python__&&__JUMP_LINK https://www.tutorialspoint.com/python/python_reg_expressions.htm
30th Apr 2018, 3:29 AM
Lord Krishna
Lord Krishna - avatar
+ 2
Yes, it will match the entire string if it does not contain a or b(including both) anywhere in the string. Try to the run and test the regex somewhere like below https://regex101.com/tests
30th Apr 2018, 6:36 AM
Lord Krishna
Lord Krishna - avatar
+ 1
is "[^ab]" correct? i dont know why you put the other stuff
30th Apr 2018, 5:49 AM
chris
chris - avatar
+ 1
so "^[^ab]+
quot; should match any string that does not contain a or b as the frist charater , last character , or in the middle of the string?
30th Apr 2018, 6:14 AM
chris
chris - avatar
+ 1
so just to clear up my mind "[^ab] " just matches strings that do not have a or b in the frist charater of the string right?
30th Apr 2018, 6:56 AM
chris
chris - avatar