Pattern eines Textes

Status
Nicht offen für weitere Antworten.

jensa

Aktives Mitglied
Hallo,
ich habe mir vorgenommen mit regulären Ausdrücken mich zu beschäftigen, jetzt bin cih auf das problem gestoßen wie ich am geschicktesten einen ganzen text parsen kann. aktuell nur das ich ** in respektive umwandel später will ich dies erweitern auf z.b. == soll zu <h1> werden etc sprich Wikisyntax in Html umwandeln hatte ich mir als beispiel genommen jetzt aber das problem das zwar der parser funktioniert er auch die ausdrücke findet jedoch entfernt er den nicht zutreffenden text komplett anstatt ihn stehen zu lassen.


Code:
public static String RegEx(String input) {

		String str,replacefirst, replacelast,output;
		Pattern p;
		Matcher m;

		output = null;
		str = input;
		p = Pattern.compile("[^*]*[**]{2}([a-zA-Z]+)[**]{2}[^*]*");
		m = p.matcher(str);
		replacefirst = "[b]";
		replacelast = "[/b]";
		while (m.find()) {
			output = replacefirst + m.group(1) + replacelast;
		}
	return output;
	}

Input ist z.B:
hallo **Jens**
wie geht es **dir**?


output sollte dann eben sein
hallo Jens
wie geht es dir?

leider ist aktuell der output:

wie kann ich nun machen das nicht treffer wo auch kein **text** halt einfach vorgehangen & wieder angehängt werden könnte?

Besten Dank für eure Hilfe im Vorraus,

Gruß jensa
 
in deiner Schleife überschreibst du jeweils den vorherigen Output,
an die Zwischenstrings zu kommen ist aber eh die schwierigere Aufgabe

da musst du eigentlich erstmal ne Menge über reguläre Ausdrücke lernen,
hier ein modifiziertes Beispiel von
http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html

Code:
public class Test
{
    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("(c)(a+)(t)");
        Matcher m = p.matcher("one cat two caaaats in the yard");
        StringBuffer sb = new StringBuffer();
        while (m.find())
        {
            m.appendReplacement(sb, "XY$2YZ");
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}
beachte die () im Pattern, die referenzierbare Gruppen darstellen,
$2 in der Schleife steht für die (a+)-Gruppe zwischen den zu ersetzenden Anfang + Ende
 
Grundsätzlich geht das mit replaceAll und Capturing Groups (in replaceAll mit $1 - $n zugreifbar).
Parser schreibt man allerdings besser nicht mit RegEx, das ist zu kompliziert und Fehleranfällig.
Schau dir mal Parser Generatoren wie AntLR an.
 
hallo,
das tool sieht interessant aus,
wie gesagt war halt primär den übungszwecken gedacht diese aufgabe, kam auf diese Idee nach einem Beitrag in einem Blog der Sich rund um das Pattern beschäftigt hatte.
funktioniert jetzt bestens.

Code:
	public static String RegEx(String input) {

		String str,output;
		Pattern p;
		Matcher m;

		output = null;
		str = input;
		p = Pattern.compile("[**]{2}([a-zA-Z]+)[**]{2}");
		m = p.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, "
$1</br>");
		}
		m.appendTail(sb);
        System.out.println(sb.toString());
		output = sb.toString();
	return output;
	}
 
replaceAll ist aber wirklich kürzer:

Code:
public class Test
{
    public static void main(String[] args)
    {
        String str = "hallo **Jens**         wie geht es **dir**?";
        str = str.replaceAll("[**]{2}([a-zA-Z]+)[**]{2}", "
$1</br>");
        System.out.println(str);
    }
}

verwendet übrigens intern genau diesen Code,
Matcher:

Code:
/**
     * Replaces every subsequence of the input sequence that matches the
     * pattern with the given replacement string.
     *
     * 

 This method first resets this matcher.  It then scans the input
     * sequence looking for matches of the pattern.  Characters that are not
     * part of any match are appended directly to the result string; each match
     * is replaced in the result by the replacement string.  The replacement
     * string may contain references to captured subsequences as in the {@link
     * #appendReplacement appendReplacement} method.
     *
     * 

 Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
     * the replacement string may cause the results to be different than if it
     * were being treated as a literal replacement string. Dollar signs may be
     * treated as references to captured subsequences as described above, and
     * backslashes are used to escape literal characters in the replacement
     * string.
     *
     * 

 Given the regular expression <tt>a*b</tt>, the input
     * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string
     * <tt>"-"</tt>, an invocation of this method on a matcher for that
     * expression would yield the string <tt>"-foo-foo-foo-"</tt>.
     *
     * 

 Invoking this method changes this matcher's state.  If the matcher
     * is to be used in further matching operations then it should first be
     * reset.  </p>
     *
     * @param  replacement
     *         The replacement string
     *
     * @return  The string constructed by replacing each matching subsequence
     *          by the replacement string, substituting captured subsequences
     *          as needed
     */
    public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                appendReplacement(sb, replacement);
                result = find();
            } while (result);
            appendTail(sb);
            return sb.toString();
        }
        return text.toString();
    }
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Zurück
Oben