Regular Expressions: How to find dashes between words

泪湿孤枕 提交于 2020-07-09 06:13:06

问题


In PCRE how to find dashes between words

e.g.

First-file-111-222.txt
This-is-the-second-file-123-456.txt
And-the-last-one-66-77.txt

So, the dash between First and and File (etc)

Then I could replace them with a space.

With ([^a-zA-Z]\d(.+)) I could select the last part (dash+nbrs) but I don't know how to mark the other dashes.

== edit the idea is to use a renamer tool (supporting regular expressions) - the rename would then to result in

First file-111-222.txt
This is the second file-123-456.txt
And the last one-66-77.txt

so, the - after the last word and between the numbers to be kept in place. only the ones between words to be replaced.


回答1:


Use look arounds:

(?i)(?<=[a-z])-(?=[a-z])

This matches dashes that have a letter preceding and a letter following.




回答2:


If I'm not missing anything following regex should work for you:

(?<=\D)-(?=\D)

It just means find a hyphen char if it is between 2 non-digit characters.

Live Demo: http://www.rubular.com/r/O2XUNaB02R




回答3:


You need to enable global mode which will find and replace every occurrence in a matching text. Here is an example: http://www.regex101.com/r/hG5rX8 (note the g in the options).

As the actual regex goes, something simple as \w-\w should suffice to get the dash.




回答4:


Is it just the dashes that you want to work on? If so, the code below should do the trick, assuming you have your input in a file called foo

perl -pe "s/-/ /g" < foo

That'll give this output:

First file 111 222.txt
This is the second file 123 456.txt
And the last one 66 77.txt

The preceding s marks that the regex is to be used to make a substitution, and the trailing g says that it's a global replacement, so the interpreter should not stop after the first match that it finds.



来源:https://stackoverflow.com/questions/16880550/regular-expressions-how-to-find-dashes-between-words

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