Regular expression with carriage return

2020-06-07 07:54发布

I'm trying to write a regular expression to extra the value which follows the word 'Total' but I'm not sure how to handle the carriage return which means i'm searching over 2 separate lines. does anyone know the best way to approach this ?

Taxes&Charges↵
↵
£ 35.97↵
↵
Total↵
£ 198.98↵
↵
£ 35.97↵
↵
↵
Total↵
£ 333.98

标签: regex
4条回答
对你真心纯属浪费
2楼-- · 2020-06-07 08:34

In regex you should use the \r to catch the carriage return and \r\n to catch the line breaks

查看更多
Animai°情兽
3楼-- · 2020-06-07 08:39

You should use regex option dot matches newline (if supported).

E.g. in .NET you could use RegexOptions.Singleline for this. It specifies single-line mode. Changes the meaning of the dot (.) so it matches every character (instead of every character except \n).

The next expression:

Regex ex = new Regex(@"(?<=Total\r\n)£\s?[\d.]+", RegexOptions.Singleline);

will match £ 198.98 and £ 333.98 values from your test example.

查看更多
在下西门庆
4楼-- · 2020-06-07 08:44

Add s modifier to your regex. s means treat string as single line. Why don't you remove carriage return with str_replace first? Oops, no PHP tag.

查看更多
戒情不戒烟
5楼-- · 2020-06-07 08:50

If you add s, to signify the single line, you can then (for example if windows) use

^Total\r\n£([ 0-9.]+)\r\n" to extract the total values.

(not tested, the brackets should ensure it appears as a group value)

查看更多
登录 后发表回答