英文:
Regular expression matching either an empty string or a string in a given set
问题
I would like to match either "direction" (">"
or "<"
) from a string like "->
", "<==
", "...
". When the string contains no direction, I want to match ""
. More precisely, the equivalent Python expression would be:
">" if ">" in s else ("<" if "<" in s else "")
I first came up with this simple regular expression:
re.search(r"[<>]|\"", s)[0]
... but it evaluates to ""
as soon as the direction is not in the first position. How would you do that?
英文:
I would like to match either "direction" (">"
or "<"
) from a string like "->"
, "<=="
, "..."
. When the string contains no direction, I want to match ""
. More precisely, the equivalent Python expression would be:
">" if ">" in s else ("<" if "<" in s else "")
I first came up with this simple regular expression:
re.search(r"[<>]|", s)[0]
... but it evaluates to ""
as soon as the direction is not in the first position. How would you do that?
答案1
得分: 4
"A simpler version of Andrej Kesely's solution:
re.search('<|>|$', s)[0]
```"
<details>
<summary>英文:</summary>
A simpler version of [Andrej Kesely](https://stackoverflow.com/users/10035985)'s solution:
```python
re.search('<|>|$', s)[0]
答案2
得分: 3
Here's the translated content without the code:
如果你想要一个纯粹的 re
解决方案(regex101):
打印:
这将匹配第一个 <
或 >
字符串或字符串的末尾 $
(然后返回空字符串 ''
)。
编辑:简化了正则表达式,感谢 @InSync
英文:
If you want pure re
solution (regex101):
import re
test_cases = [
"->", "<==", "..."
]
for t in test_cases:
print(re.search('(?=[<>]).|$', t)[0])
Prints:
>
<
This will match first <
or >
string or end of string $
(then it returns empty string ''
)
EDIT: Simplified the regex, thanks @InSync
答案3
得分: 2
The reason this regex [<>]|
returns "" if the first character is not <
or >
is because the alternation in this case always matches the position, returning a zero length match for re.search
Instead of writing if/else statements or a regex, you could also use next() which can return a default value and list the strings that you want to match in an array:
test_str = "this is a test string with > and <"
items = ["<", ">"]
item = next((i for i in items if i in test_str), "")
print(item)
英文:
The reason this regex [<>]|
returns "" if the first character is not <
or >
is because the alternation in this case always matches the position, returning a zero length match for re.search
Instead of writing if/else statements or a regex, you could also use next() which can return a default value and list the strings that you want to match in an array:
test_str = "this is a test string with > and <"
items = ["<", ">"]
item = next((i for i in items if i in test_str), "")
print(item)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论