2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.transform.regex.internal;
15 import java.util.regex.Matcher;
16 import java.util.regex.Pattern;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.core.transform.TransformationException;
21 import org.openhab.core.transform.TransformationService;
22 import org.osgi.service.component.annotations.Component;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
28 * The implementation of {@link TransformationService} which transforms the input by Regular Expressions.
31 * <b>Note:</b> the given Regular Expression must contain exactly one group!
33 * @author Thomas.Eichstaedt-Engelen - Initial contribution
36 @Component(property = { "openhab.transform=REGEX" })
37 public class RegExTransformationService implements TransformationService {
39 private final Logger logger = LoggerFactory.getLogger(RegExTransformationService.class);
41 private static final Pattern SUBSTR_PATTERN = Pattern.compile("^s/(.*?[^\\\\])/(.*?[^\\\\])/(.*)$");
44 public @Nullable String transform(String regExpression, String source) throws TransformationException {
45 if (regExpression == null || source == null) {
46 throw new TransformationException("the given parameters 'regex' and 'source' must not be null");
49 logger.debug("about to transform '{}' by the function '{}'", source, regExpression);
53 Matcher substMatcher = SUBSTR_PATTERN.matcher(regExpression);
54 if (substMatcher.matches()) {
55 logger.debug("Using substitution form of regex transformation");
56 String regex = substMatcher.group(1);
57 String substitution = substMatcher.group(2);
58 String options = substMatcher.group(3);
59 if ("g".equals(options)) {
60 result = source.trim().replaceAll(regex, substitution);
62 result = source.trim().replaceFirst(regex, substitution);
69 Matcher matcher = Pattern.compile("^" + regExpression + "$", Pattern.DOTALL).matcher(source.trim());
70 if (!matcher.matches()) {
72 "the given regex '^{}$' doesn't match the given content '{}' -> couldn't compute transformation",
73 regExpression, source);
78 while (matcher.find()) {
79 if (matcher.groupCount() == 0) {
81 "the given regular expression '^{}$' doesn't contain a group. No content will be extracted and returned!",
86 result = matcher.group(1);
88 if (matcher.groupCount() > 1) {
90 "the given regular expression '^{}$' contains more than one group. Only the first group will be returned!",