简体   繁体   中英

RegEx - Get value from between two strings ignoring white space

I've got a string that looks a bit like this : blah Wt 10.35 kg blah

And I'm using : (?<=Wt)(.*?)(?=kg)

To get the value of the weight (between Wt and kg) - but it's also pulling the white space from either side.

Can anyone tell me please how I can tweak the expression to just give me back the value and not the white space.

Since you're using a group anyways, you may just add a non-capturing group:

(?<=Wt)(?:\\s*)(.*?)(?:\\s*)(?=kg)

\\s* will match zero or more whitespace characters.

try to use (?<=Wt)\\s+(.*?)\\s+(?=kg)

The \\s+ should eat out white spaces and leave just the value.

Documentation

put the spaces in the lookarounds:

(?<=Wt\s*)(\S+)(?=\s*kg)

Since you use the .net framework you can use a variable length lookbehind (which is often forbidden in other regex flavour)

\\s is the character class for white characters (spaces, tab, newlines)

\\S means all that is not in \\s

I used \\S+ instead of .*? to avoid a lazy quantifier, and to trim spaces around the target substring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM