该方法删除一字符串中所有匹配某一规则字串
可用于清理一个字符串中的空白符和语气助词

@param target 待处理字符串
@param rules 删除规则
@return 清理工作完成后的字符串
193371
public static String delKeyword(String target, String rules){
		Pattern p = Pattern.compile(rules); 
		Matcher m = p.matcher(target); 
		StringBuffer sb = new StringBuffer(); 
		boolean result = m.find(); 
		while(result) { 
			m.appendReplacement(sb, ""); 
			result = m.find(); 
		}
		m.appendTail(sb);
		String s = sb.toString();
		//System.out.println("字符串："+target+" 的处理后字符串为：" +sb);
		return s;
	}
302304
public static Betner betnNext(String target, String leftSameWithRight) {
		return betn(target).betweenNext(leftSameWithRight);
	}
13571
@SuppressWarnings("unchecked") // NOSONAR (Avoid Duplicate Literals)
    private void processAllRulesWithEachResultHandler(RI ruleInput) {
        // For each rule
        List<Object> combinedRulesOutput = new ArrayList<Object>(rules.size());
        for (Rule<RI, RO> rule : rules) {
            // Validate the data and get the rule output
            Object data = rule.validate(ruleInput);

            // Transform the rule output
            if (ruleOutputTransformers != null) {
                for (Transformer transformer : ruleOutputTransformers) {
                    data = transformer.transform(data);
                }
            }

            // Put the transformed rule output in a list
            combinedRulesOutput.add(data);
        }

        // Transform the list of transformed rule output to result handler input
        Object ruleOutput = combinedRulesOutput;
        if (resultHandlerInputTransformers != null) {
            for (Transformer transformer : resultHandlerInputTransformers) {
                ruleOutput = transformer.transform(ruleOutput);
            }
        }
        RHI resultHandlerInput = (RHI) ruleOutput;

        // Process the result handler input with the result handlers
        processResultHandlers(resultHandlerInput);
    }
109978
public static Set<String> validateAsRuleBody(Conjunction<Pattern> pattern, Rule rule, TransactionOLTP graph){
        Set<String> errors = new HashSet<>();
        try{
            CompositeQuery body = ReasonerQueries.composite(pattern, graph);
            Set<ResolvableQuery> complementQueries = body.getComplementQueries();
            if(complementQueries.size() > 1){
                errors.add(ErrorMessage.VALIDATION_RULE_MULTIPLE_NEGATION_BLOCKS.getMessage(rule.label()));
            }
            if(!body.isPositive() && complementQueries.stream().noneMatch(ReasonerQuery::isPositive)){
                errors.add(ErrorMessage.VALIDATION_RULE_NESTED_NEGATION.getMessage(rule.label()));
            }
        } catch (GraqlQueryException e) {
            errors.add(ErrorMessage.VALIDATION_RULE_INVALID.getMessage(rule.label(), e.getMessage()));
        }
        return errors;
    }
1176556
public static List<ExternalGraphic> externalGraphicsFromRule( Rule rule ) {
        List<ExternalGraphic> gList = new ArrayList<ExternalGraphic>();
        List<Symbolizer> symbolizers = rule.symbolizers();
        if (symbolizers.size() != 0) {
            for( Symbolizer symbolizer : symbolizers ) {
                Graphic[] graphics = new Graphic[2];
                if (symbolizer instanceof PointSymbolizer) {
                    PointSymbolizer pointSymbolizer = (PointSymbolizer) symbolizer;
                    graphics[0] = pointSymbolizer.getGraphic();
                } else if (symbolizer instanceof LineSymbolizer) {
                    LineSymbolizer lineSymbolizer = (LineSymbolizer) symbolizer;
                    Stroke stroke = lineSymbolizer.getStroke();
                    graphics[0] = stroke.getGraphicStroke();
                } else if (symbolizer instanceof PolygonSymbolizer) {
                    PolygonSymbolizer polygonSymbolizer = (PolygonSymbolizer) symbolizer;
                    Stroke stroke = polygonSymbolizer.getStroke();
                    if (stroke != null)
                        graphics[0] = stroke.getGraphicStroke();
                    Fill fill = polygonSymbolizer.getFill();
                    if (fill != null)
                        graphics[1] = fill.getGraphicFill();
                }
                for( int i = 0; i < graphics.length; i++ ) {
                    if (graphics[i] != null) {
                        for( GraphicalSymbol gs : graphics[i].graphicalSymbols() ) {
                            if ((gs != null) && (gs instanceof ExternalGraphic)) {
                                ExternalGraphic externalGraphic = (ExternalGraphic) gs;
                                gList.add(externalGraphic);
                            }
                        }
                    }
                }
            }
            return gList;
        }
        return Collections.emptyList();
    }
1236390
public static boolean contains(String target, List<String> containWith) {
		if (isNull(target)) {
			return false;
		}
		
		return matcher(target).contains(containWith);
	}
971167
private static void cleanEmptyLeafs(LogicClause clause)
  {
    if(clause == null || clause.getOp() == LogicClause.Operator.LEAF)
    {
      return;
    }
    
    LinkedList<LogicClause> childListCopy = new LinkedList<>(clause.getChildren());
    
    clause.clearChildren();
    
    ListIterator<LogicClause> itChildren = childListCopy.listIterator();
    while(itChildren.hasNext())
    {
      LogicClause n = itChildren.next();
      
      // don't add empty leafs, add everything else
      if(!(n.getOp() == LogicClause.Operator.LEAF && n.getContent() == null)) 
      {
        clause.addChild(n);
      }
    }
    
    // clean all sub clauses
    for(LogicClause c : clause.getChildren())
    {
      cleanEmptyLeafs(c);
    }
  }
555316
static Rule[] getOrderedRules(final Rule[] rules) {

        final Comparator<Rule> c = Comparator.comparing(Rule::getSize).reversed().thenComparing(Rule::getPattern);

        final Rule[] result = Arrays.copyOf(rules, rules.length);
        parallelSort(result, c);
        return result;
    }
680760
private void unmapResultHandlerFromAllRules(final RH resultHandler) {
        if (resultHandler != null) {
            for (final List<RH> mappedResultHandlers : rulesToResultHandlers.values()) {
                mappedResultHandlers.remove(resultHandler);
            }
        }
    }
1067707
public List<Error> validate(Object target) {
		DeleteItemRequest instance = (DeleteItemRequest) target;
		List<Error> errors = ValidatorUtils.invokeValidator(new TableNameValidator(), instance.getTableName());
		errors.addAll(ValidatorUtils.invokeValidator(new KeyValidator(), instance.getKey()));
		if (instance.getExpected() != null) {
			errors.addAll(ValidatorUtils.invokeValidator(new ExpectedValidator(), instance.getExpected()));
		}
		if (instance.getReturnValues() != null) {
			errors.addAll(ValidatorUtils.rejectIfNotMatchRegex(instance.getReturnValues(), "^(NONE|ALL_OLD)$"));
		}
		return removeNulls(errors);
	}
704761
public void process(StringBuilder buf, NFRuleSet ruleSet) {
        // markers depend on what rule set we are using

        // Commented by johnvu on the if statement since lastRuleSet is never initialized
        //if (ruleSet != lastRuleSet) {
            String name = ruleSet.getName();
            for (int i = 0; i < rulesetNames.length; ++i) {
                if (rulesetNames[i].equals(name)) {
                    format = i;
                    longForm = i == 1 || i == 3;
                    break;
                }
            }
        //}

        if (longForm) {
            for (int i = buf.indexOf("*"); i != -1; i = buf.indexOf("*", i)) {
                buf.delete(i, i+1);
            }
            return;
        }

        final String DIAN = "\u9ede"; // decimal point

        final String[][] markers = {
            { "\u842c", "\u5104", "\u5146", "\u3007" }, // marker chars, last char is the 'zero'
            { "\u4e07", "\u4ebf", "\u5146", "\u3007" },
            { "\u842c", "\u5104", "\u5146", "\u96f6" }
            // need markers for time?
        };

        // remove unwanted lings
        // a '0' (ling) with * might be removed
        // mark off 10,000 'chunks', markers are Z, Y, W (zhao, yii, and wan)
        // already, we avoid two lings in the same chunk -- ling without * wins
        // now, just need  to avoid optional lings in adjacent chunks
        // process right to left

        // decision matrix:
        // state, situation
        //     state         none       opt.          req.
        //     -----         ----       ----          ----
        // none to right     none       opt.          req.  
        // opt. to right     none   clear, none  clear right, req.
        // req. to right     none   clear, none       req.

        // mark chunks with '|' for convenience
        {
            String[] m = markers[format];
            for (int i = 0; i < m.length-1; ++i) {
                int n = buf.indexOf(m[i]);
                if (n != -1) {
                    buf.insert(n+m[i].length(), '|');
                }
            }
        }

        int x = buf.indexOf(DIAN);
        if (x == -1) {
            x = buf.length();
        }
        int s = 0; // 0 = none to right, 1 = opt. to right, 2 = req. to right
        int n = -1; // previous optional ling
        String ling = markers[format][3];
        while (x >= 0) {
            int m = buf.lastIndexOf("|", x);
            int nn = buf.lastIndexOf(ling, x);
            int ns = 0;
            if (nn > m) {
                ns = (nn > 0 && buf.charAt(nn-1) != '*') ? 2 : 1;
            }
            x = m - 1;

            // actually much simpler, but leave this verbose for now so it's easier to follow
            switch (s*3+ns) {
            case 0: /* none, none */
                s = ns; // redundant
                n = -1;
                break;
            case 1: /* none, opt. */
                s = ns;
                n = nn; // remember optional ling to right
                break;
            case 2: /* none, req. */
                s = ns;
                n = -1;
                break;
            case 3: /* opt., none */
                s = ns;
                n = -1;
                break;
            case 4: /* opt., opt. */
                buf.delete(nn-1, nn+ling.length()); // delete current optional ling
                s = 0;
                n = -1;
                break;
            case 5: /* opt., req. */
                buf.delete(n-1, n+ling.length()); // delete previous optional ling
                s = ns;
                n = -1;
                break;
            case 6: /* req., none */
                s = ns;
                n = -1;
                break;
            case 7: /* req., opt. */
                buf.delete(nn-1, nn+ling.length()); // delete current optional ling
                s = 0;
                n = -1;
                break;
            case 8: /* req., req. */
                s = ns;
                n = -1;
                break;
            default:
                throw new IllegalStateException();
            }
        }

        for (int i = buf.length(); --i >= 0;) {
            char c = buf.charAt(i);
            if (c == '*' || c == '|') {
                buf.delete(i, i+1);
            }
        }
    }
130159
public static boolean endAny(String target, List<String> endWith) {
		if (isNull(target)) {
			return false;
		}
		
		return matcher(target).ends(endWith);
	}
303685
@Override
    public BufferByteOutput<T> target(final T target) {
        return (BufferByteOutput<T>) super.target(target);
    }
1339978
public static void removeRule( TerminalNode tn, Collection<InternalWorkingMemory> wms, InternalKnowledgeBase kBase) {
        if (log.isTraceEnabled()) {
            log.trace("Removing Rule {}", tn.getRule().getName());
        }

        boolean hasProtos = kBase.hasSegmentPrototypes();
        boolean hasWms = !wms.isEmpty();

        if (!hasProtos && !hasWms) {
            return;
        }

        RuleImpl      rule       = tn.getRule();
        LeftTupleNode firstSplit = getNetworkSplitPoint(tn);
        PathEndNodes pathEndNodes = getPathEndNodes(kBase, firstSplit, tn, rule, hasProtos, hasWms);

        for (InternalWorkingMemory wm : wms) {
            wm.flushPropagations();

            PathEndNodeMemories tnms = getPathEndMemories(wm, pathEndNodes);

            if ( !tnms.subjectPmems.isEmpty() ) {
                if (NodeTypeEnums.LeftInputAdapterNode == firstSplit.getType() && firstSplit.getAssociationsSize() == 1) {
                    if (tnms.subjectPmem != null) {
                        flushStagedTuples(firstSplit, tnms.subjectPmem, wm);
                    }

                    processLeftTuples(firstSplit, wm, false, tn.getRule());

                    removeNewPaths(wm, tnms.subjectPmems);
                } else {
                    flushStagedTuples(tn, tnms.subjectPmem, pathEndNodes, wm);

                    processLeftTuples(firstSplit, wm, false, tn.getRule());

                    removeNewPaths(wm, tnms.subjectPmems);

                    Map<PathMemory, SegmentMemory[]> prevSmemsLookup = reInitPathMemories(tnms.otherPmems, tn);

                    // must collect all visited SegmentMemories, for link notification
                    Set<SegmentMemory> smemsToNotify = handleExistingPaths(tn, prevSmemsLookup, tnms.otherPmems, wm, ExistingPathStrategy.REMOVE_STRATEGY);

                    notifySegments(smemsToNotify, wm);
                }
            }

            if (tnms.subjectPmem != null && tnms.subjectPmem.isInitialized() && tnms.subjectPmem.getRuleAgendaItem().isQueued()) {
                // SubjectPmem can be null, if it was never initialized
                tnms.subjectPmem.getRuleAgendaItem().dequeue();
            }
        }
    }
1123757
private void simplify(PatternRule rule, List<String> xmlLines) {
    List<Integer> linesToRemove = new ArrayList<>();
    String currentRuleId = null;
    Pattern pattern = Pattern.compile(".*id=[\"'](.*?)[\"'].*");
    String expectedSubId = rule.getSubId();
    int lineCount = 0;
    int subRuleCount = 0;
    int removedCount = 0;
    boolean inRuleGroup = false;
    String newRegex = null;
    boolean inAntiPattern = false;
    for (lineCount = 0; lineCount < xmlLines.size(); lineCount++) {
    //for (String xmlLine : xmlLines) {
      String xmlLine = xmlLines.get(lineCount);
      if (xmlLine.contains("<rulegroup")) {
        subRuleCount = 0;
        inRuleGroup = true;
      } else if (xmlLine.contains("</rulegroup>")) {
        subRuleCount = 0;
        inRuleGroup = false;
      } else if ((xmlLine.contains("<rule ")||xmlLine.contains("<rule>")) && inRuleGroup) {
        subRuleCount++;
      }
      Matcher m = pattern.matcher(xmlLine);
      if (m.matches()) {
        currentRuleId = m.group(1);
      }
      if (currentRuleId != null && !currentRuleId.equals(rule.getId())) {
        continue;
      }
      if (!inRuleGroup) {
        subRuleCount = 1;
      }
      if (!expectedSubId.equals("0") && !expectedSubId.equals(String.valueOf(subRuleCount))) {
        continue;
      }
      if (xmlLine.matches(".*<antipattern.*")) {
        inAntiPattern = true;
      }
      if (inAntiPattern) {
        continue;
      }
      if (xmlLine.matches(".*</antipattern.*")) {
        inAntiPattern = false;
        continue;
      }
      if (xmlLine.matches(".*<(token|pattern).*") || xmlLine.matches("\\s*</?marker>.*")) {
        linesToRemove.add(lineCount);
      }
      if (xmlLine.matches(".*</pattern.*")) {
        linesToRemove.add(lineCount);
        int lastTokenIndent = xmlLine.indexOf("<");
        newRegex = Strings.repeat(" ", lastTokenIndent) + getRegex(rule);
      }
    }
    Collections.reverse(linesToRemove); // start from end, as we need to remove items
    for (Integer s : linesToRemove) {
      xmlLines.remove(s.intValue());
      removedCount++;
    }
    if (removedCount == 0) {
      System.err.println("No line removed: " + rule + "[" + expectedSubId + "]");
    } else {
      xmlLines.add(linesToRemove.get(linesToRemove.size()-1), newRegex);
      touchedRulesCount++;
    }
  }
1314292
private void removeLinesFromXml(Rule rule, String sentenceToRemove, List<String> xmlLines) {
    List<Integer> linesToRemove = new ArrayList<>();
    String currentRuleId = null;
    Pattern pattern = Pattern.compile(".*id=[\"'](.*?)[\"'].*");
    String expectedSubId = ((AbstractPatternRule) rule).getSubId();
    int lineCount = 0;
    int subRuleCount = 0;
    int removedCount = 0;
    boolean inRuleGroup = false;
    for (String xmlLine : xmlLines) {
      if (xmlLine.contains("<rulegroup")) {
        subRuleCount = 0;
        inRuleGroup = true;
      } else if (xmlLine.contains("</rulegroup>")) {
        subRuleCount = 0;
        inRuleGroup = false;
      } else if ((xmlLine.contains("<rule ")||xmlLine.contains("<rule>")) && inRuleGroup) {
        subRuleCount++;
      }
      Matcher m = pattern.matcher(xmlLine);
      if (m.matches()) {
        currentRuleId = m.group(1);
      }
      if (!xmlLine.contains("correction=") && xmlLine.contains(sentenceToRemove + "</example>")) {
        if (currentRuleId != null && !currentRuleId.equals(rule.getId())) {
          lineCount++;
          continue;
        }
        if (!inRuleGroup) {
          subRuleCount = 1;
        }
        if (!expectedSubId.equals("0") && !expectedSubId.equals(String.valueOf(subRuleCount))) {
          lineCount++;
          continue;
        }
        linesToRemove.add(lineCount);
        break;
      }
      lineCount++;
    }
    Collections.reverse(linesToRemove); // start from end, as we need to remove items
    for (Integer s : linesToRemove) {
      xmlLines.remove(s.intValue());
      removedLinesCount++;
      removedCount++;
    }
    if (removedCount == 0) {
      System.err.println("No line removed: " + rule + "[" + expectedSubId + "]");
    }
  }
566162
@SuppressWarnings("TryWithIdenticalCatches")
	private static Map<View, FormValidator.FieldInfo> findFieldsToValidate(Object target) {
		final Field[] fields = target.getClass().getDeclaredFields();
		if (fields == null || fields.length == 0) {
			return Collections.emptyMap();
		}

		final WeakHashMap<View, FormValidator.FieldInfo> infoMap = new WeakHashMap<>(fields.length);
		for (Field field : fields) {
			final List<FormValidator.ValidationInfo> infos = new ArrayList<>();
			final Annotation[] annotations = field.getDeclaredAnnotations();
			if (annotations.length > 0) {
				if (! View.class.isAssignableFrom(field.getType())) {
					// next field
					continue;
				}
				final View view;
				try {
					field.setAccessible(true);
					view = (View) field.get(target);
				} catch (IllegalAccessException e) {
					throw new FormsValidationException(e);
				}
				if (view == null) {
					continue;
				}

				for (Annotation annotation : annotations) {
					final IValidator validator;
					try {
						validator = ValidatorFactory.getValidator(annotation);
					} catch (IllegalAccessException e) {
						throw new FormsValidationException(e);
					} catch (InstantiationException e) {
						throw new FormsValidationException(e);
					}
					if (validator != null) {
						FormValidator.ValidationInfo info = new FormValidator.ValidationInfo(annotation, validator);
						infos.add(info);
					}
				}

				final Condition conditionAnnotation = field.getAnnotation(Condition.class);
				if (infos.size() > 0) {
					Collections.sort(infos, new Comparator<FormValidator.ValidationInfo>() {
						@Override
						public int compare(FormValidator.ValidationInfo lhs, FormValidator.ValidationInfo rhs) {
							return lhs.order < rhs.order ? -1 : (lhs.order == rhs.order ? 0 : 1);
						}
					});
				}
				final FormValidator.FieldInfo fieldInfo = new FormValidator.FieldInfo(conditionAnnotation, infos);
				infoMap.put(view, fieldInfo);
			}
		}
		return infoMap;
	}