java - Split around character with regex and conditions -


i try split string following conditions

  • keep characters
  • split around = if preceding character not % or !
  • split around !=

example:

test=45 -> [test, =, 45]
test!=45 -> [test, !=, 45]
test%=45 -> [test%=45]

code:

private static final map<string[], string> tests = new hashmap<>();  static {     tests.put(new string[]{"test", "=", "45"}, "test=45");     tests.put(new string[]{"test", "!=", "45"}, "test!=45");     tests.put(new string[]{"test%=45"}, "test%=45");     tests.put(new string[]{"test", "=", "%=45"}, "test=%=45");     tests.put(new string[]{"test%=", "=", "%=45"}, "test%==%=45"); }  @org.junit.test public void simpletest() {     string regex = "(?=!=)|(?<=!=)|(?<![!%])((?<==)|(?==))";     (map.entry<string[], string> entry : tests.entryset()) {         assert.assertarrayequals(entry.getkey(), entry.getvalue().split(regex));     } } 

the "best" thing found (?=!=)|(?<=!=)|(?<![!%])((?<==)|(?==)) don't know why %= split after ((?<==) seems executed)
left , right characters can of acii table.

result :

test=45 -> [test, =, 45]
test!=45 -> [test, !=, 45]
test%=45 -> [test%=, 45] <- should [test%=45]
test=%=45 -> [test, =, %=, 45] <- should [test, =, %=45]
test%==%=45 -> [test%=, =, %=, 45] <- should [test%=, =, %=45]

is possible regex , split ?

note: part of regex , it's used "easily" parse data, yes can simple code instead of using regex , split not i'm asking for.

you need move lookbehind lookarounds checking equal sign presence:

(?<=!=)|(?=!=)|((?<=(?<![!%])=)|(?=(?<![!%])=)) 

see this demo

i modified part: ((?<=(?<![!%])=)|(?=(?<![!%])=)).

(   (?<=(?<![!%])=) - matches location preceded = sign not preceded ! or %  |  (?=(?<![!%])=) - matches location followed = sign not preceded ! or % ) 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -