How to get the first value of the string

I would like to get the first value after Total in a text file, able to extract the whole line of data after Total using the below regex method.

(System.Text.RegularExpressions.Regex.Match(Text1,"(?<=Total ).+").Value)

May I know how could I do if I only want to extract the first value after total?

The data is something similar like this:

Total 123 456 789
(I only want to get 123)

It works when I use the below code to get 789, but I do not know how to get 123.
(System.Text.RegularExpressions.Regex.Match(Text1,"(?<=Total ).+").Value).ToString.Split(" "C).last

Anyone can help please?

you can use stringVal.substring(0, stringVal.indexOf(" "))

Hi,

Can you try the following expressions?

System.Text.RegularExpressions.Regex.Match(Text1,"(?<=Total ).+?(?=\s)").Value

or

(System.Text.RegularExpressions.Regex.Match(Text1,"(?<=Total ).+").Value).ToString.Split(" "C).First

Regards,

Hi @Yoichi
Both captured blank spaces. The blank spaces between are inconsistent, could this affect the coding you provided?

Hi @Furqan Have tried this and it captured blank spaces too.

Hi,

Do you mean the string might have 2 or more continuous spaces? If so the following helps you.

System.Text.RegularExpressions.Regex.Match(Text1,"(?<=Total\s*)\S+?(?=\s)").Value

Regards,

Thanks @Yoichi

It works as expected =) Do you mind to explain on what does this (?<=Total\s*)\S+?(?=\s) part of expression means?

1 Like

Hi,

Do you mind to explain on what does this (?<=Total\s*)\S+?(?=\s) part of expression means?

(?<=Total\s*) is lookbehind of regex, it means “Total” and \s* (=any whitespaces) will be matched as lookbehind. (it will not be contained in the result)

\S+? means one or more NON-whitespaces and matched as result. (it might be good as \S+)

'(?=\s) is lookahead of regex, it means \s (=any white space) will be matched as lookahead. (it will not be contained in the result)

Regards,

1 Like

@Yoichi Thank you! =)

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.