Extract css property values using simple java code

Please check following code.

Pattern pxPattern = Pattern.compile("^.*[0-9]+(%|pt|em).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(0));

i want to substract string 445em. i am using code for checking css. means i wants to extract

just values like 45em or 50%.

Thanks.

Answers


First, the captured group is in group 1, not group 0. Then you need to modify your regex to not consume the numbers and include them in the group. Try:

Pattern pxPattern = Pattern.compile("^.*?([0-9]+(?:%|pt|em)).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(1));

EDIT:

To get all values from a string with several, you can use this pattern:

Pattern pxPattern = Pattern.compile("[0-9]+(?:%|pt|em)");
Matcher pxMatcher = pxPattern.matcher("margin: 0pt, 6em, 5%, 2pt");
List<String> propertyValues = new ArrayList<String>();
while (pxMatcher.find()) {
    propertyValues.add(pxMatcher.group());
}

Need Your Help

how to use SET and COPY in CMD?

c# copy cmd set

working on this in C# Win Forms.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.