Home > Software design >  How to write regular expression to check if substring starts with range of characters?
How to write regular expression to check if substring starts with range of characters?

Time:03-12

Thanks for your help in advance.

I want to check if a substring would start within range of characters after a prefix

For example, I have the following strings with prefix 'abc_xyz$'

abc_xyz$Item Ledger_Entry_CT
abc_xyz$Purchase

To check if string after prefix would start G thru R, I have written the following regular expression,

abc_xyz\$^[G-Rg-r].*

Unfortunately it does not help.

Here are use cases

abc_xyz$Item Ledger_Entry_CT --> should match since first char in 'Item' matches thru G and R
abc_xyz$Purchase --> should match since first char in 'Purchase' matches thru G and R
abc_xyz$Customer --> should NOT match since first char in 'Customer' do not match thru G and R
abc_xyz$Sales --> should NOT match since first char in 'Sales' do not match thru G and R

Any help?

CodePudding user response:

You need to use

^abc_xyz\$[G-Rg-r].*
^abc_xyz\$(?i:[g-r]).*
^abc_xyz\$(?i)[g-r].*

See the regex demo.

The pattern matches

  • ^ - start of string
  • abc_xyz\$ - a abc_xyz$ fixed string
  • [G-Rg-r] - G to R or g to r letters
  • .* - the rest of the line.

Note the (?i:[g-r]) inline modifier group makes the [g-r] pattern part case insensitive.

The (?i) part makes all the pattern parts to the right of it case insensitive.

  • Related