从正则表达式匹配组中删除尾随空格
我通过 iPhone 上的 RegKit 使用正则表达式 lib icucore 替换大字符串中的模式。
我正在寻找的模式看起来像这样
| hello world (P1)|
我将此模式与以下正则表达式相匹配
\|((\w*|.| )+)\((\w\d+)\)\|
这会在找到匹配项时将输入字符串转换为 3 组,其中组 1(字符串)和组 3(字符串中)括号)是我感兴趣的。
我正在将这些格式化字符串转换为 html 链接,因此上面的内容将转换为
<a href="P1">Hello world </a>
“我的问题是第三组中的尾随空格”。当链接突出显示并加下划线时,会导致线条超出打印字符。
虽然我知道我可以提取所有匹配项并手动处理它们,但使用 icu 库的搜索和替换功能是一个更干净的解决方案,因此我宁愿不这样做。
一如既往地非常感谢
I'm using regular expression lib icucore via RegKit on the iPhone to
replace a pattern in a large string.
The Pattern i'm looking for looks some thing like this
| hello world (P1)|
I'm matching this pattern with the following regular expression
\|((\w*|.| )+)\((\w\d+)\)\|
This transforms the input string into 3 groups when a match is found, of which group 1(string) and group 3(string in parentheses) are of interest to me.
I'm converting these formated strings into html links so the above would be transformed into
<a href="P1">Hello world </a>
My problem is the trailing space in the third group. Which when the link is highlighted and underlined, results with the line extending beyond the printed characters.
While i know i could extract all the matches and process them manually, using the search and replace feature of the icu lib is a much cleaner solution, and i would rather not do that as a result.
Many thanks as always
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下可以作为替代正则表达式吗?
\|((\w*|.| )+)\s+\((\w\d+)\)\|
插入额外的 \s+ 会将空格拉到第一个分组之外。不过,考虑到你的例子&正则表达式,我不知道为什么你不这样做:
\|(.+)\s+\((\w\d+)\)\|
这将具有相同的效果。然而,你原来的正则表达式和我的更简单的正则表达式都会失败,但是在:
|你好世界(P1)|并在同一条线上 |你好,世界 (P1)|
它将把它汇总成 1 场比赛。
Would the following work as an alternate regular expression?
\|((\w*|.| )+)\s+\((\w\d+)\)\|
Where inserting the extra \s+ pulls the space outside the 1st grouping.Though, given your example & regex, I'm not sure why you don't just do:
\|(.+)\s+\((\w\d+)\)\|
Which will have the same effect. However, both your original regex and my simpler one would both fail, however on:
| hello world (P1)| and on the same line | howdy world (P1)|
where it would roll it up into 1 match.
会将尾随空格放在捕获组之外。当然,只有当总是有一个空格时,这才有效。你能保证吗?
如果不是,请使用
这使用后行断言来确保捕获组以非空格字符结尾。
will put the trailing space(s) outside the capturing group. This will of course only work if there always is a space. Can you guarantee that?
If not, use
This uses a lookbehind assertion to make sure the capturing group ends in a non-space character.