Search strings and line breaks with pyUNO

∥☆過路亽.° 提交于 2020-01-30 08:52:20

问题


I would like to delete a specific string from a document. I manage to delete the content of the string, but the line break still remains after. I found some things about ControlCharacters but it seems they are only numeric constants. Is it actually useful?

This works.

r = oDoc.createReplaceDescriptor()
r.setSearchString("FOOBAR")
r.setReplaceString("OTHERSTUFF")
oDoc.replaceAll(r)

This does not

r = oDoc.createReplaceDescriptor()
r.setSearchString("FOOBAR\n")
r.setReplaceString("OTHERSTUFF")
oDoc.replaceAll(r)
r = oDoc.createReplaceDescriptor()
r.setSearchString("FOOBAR\r")
r.setReplaceString("OTHERSTUFF")
oDoc.replaceAll(r)

How do I delete the whole line, including the line break?


回答1:


According to the built in help:

A search using a regular expression will work only within one paragraph. To search using a regular expression in more than one paragraph, do a separate search in each paragraph.

I interpret this to mean that newline characters cannot be searched for. Instead, loop through the search results and delete the character. Here is some code that does this:

search = oDoc.createSearchDescriptor()
search.SearchRegularExpression = True
search.SearchString = "FOOBAR$"
selsFound = oDoc.findAll(search)
for sel_index in range(0, selsFound.getCount()):
    oSel = selsFound.getByIndex(sel_index)
    try:
        oCursor = oSel.getText().createTextCursorByRange(oSel)
    except (RuntimeException, IllegalArgumentException):
        return
    oCursor.setString("")  # delete
    oCursor.goRight(1, True) # select newline character
    oCursor.setString("")  # delete


来源:https://stackoverflow.com/questions/33912147/search-strings-and-line-breaks-with-pyuno

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!