Home > Net >  moving characters by using regex
moving characters by using regex

Time:12-20

I'm trying to move matched characters to the end of sentence.

from

300p apple in house
orange 200p in school

to

apple in house 300p
orange in school 200p

So I matched (. )([\d] p)(. )$ and substituted with \1 \3 \2. But the result is like

30  apple in house 0p
orange 20  in school 0p 

I also checked greedy concept, but I don't know what is problem. How can I fix this?

CodePudding user response:

You can use

^(.*?)(\d p) *(. )

Replace with \1\3 \2.

See the regex demo. Details:

  • ^ - start of string (or line if you use a multiline mode)
  • (.*?) - Group 1: any zero or more chars other than line break chars as few as possible
  • (\d p) - Group 2: one or more digits, and then a p char
  • * - zero or more spaces
  • (. ) - Group 3: any one or more chars other than line break chars as many as possible (since it is a greedy subpattern, no $ anchor is required, the match will go up to the end of string (or line if you use a multiline mode)).

CodePudding user response:

With your shown samples only, please try following regex.

^(\D )?(\d p)\s*(. )$

Online demo for above regex

Explanation:

^(\D )?  ##Matching from starting and creating 1st capturing group which has all non-digits in it and keeping it as optional.
(\d p)   ##Creating 2nd capturing group which matches 1 or more digits followed by p here.
\s*      ##Matching 0 or more occurrences of spaces here.
(. )$    ##Creating 3rd capturing group here which has everything in it.
  • Related